25

How can I get Python to display the time in eastern?

I've looked over the python documentation but it's pretty confusing. I'm using Python 3.

Muhammad Dyas Yaskur
  • 6,914
  • 10
  • 48
  • 73
Hyzenthlay
  • 463
  • 1
  • 7
  • 12
  • 4
    This might help: http://stackoverflow.com/questions/117514/how-do-i-use-timezones-with-a-datetime-object-in-python Basically, use UTC internally and use PyTZ to convert to a particular timezone when displaying. – li.davidm Jul 29 '12 at 15:34

5 Answers5

51

There is a much more intuitive way, of course:

from datetime import datetime
from pytz import timezone
tz = timezone('EST')
datetime.now(tz) 
## this returns a datetime object pointing to right now 
## according to the timezone info object handed in as the tz variable. 

Alternatively you can define your own datetime object and pass in tz as tzinfo, as you can see below:

datetime(2016, 3, 30, 11, 13, 24, tzinfo=tz)
ballade4op52
  • 2,142
  • 5
  • 27
  • 42
bmbigbang
  • 1,318
  • 1
  • 10
  • 15
  • This is exactly what I was looking for. However I ran the above (date of this comment and I'm on the East Coast). And its showing the following (I'm guessing this is a daylight savings issues): print datetime.now(tz) ---> Out[23]: datetime.datetime(2016, 4, 22, 12, 19, 20, 281778, tzinfo=) print datetime.now() ----- > Out[24]: datetime.datetime(2016, 4, 22, 13, 19, 58, 839327) – robertwest Apr 22 '16 at 17:26
  • 8
    Using 'US/Eastern' instead of 'EST' seems to resolve this – robertwest Apr 22 '16 at 17:29
  • not sure what can cause a 38minute offset though it may be that your local system has a different set of timezones. for a list have a look at http://stackoverflow.com/questions/13866926/python-pytz-list-of-timezones – bmbigbang Apr 29 '16 at 11:14
9

You should use the package pytz if you'll be needing a lot of time zones, and you need to correctly handle the duplicate hour of daylight savings time (i.e. what happens from midnight to 1am).

For something simple though, it's easy enough to create your own time zone class:

import datetime

class EST5EDT(datetime.tzinfo):

    def utcoffset(self, dt):
        return datetime.timedelta(hours=-5) + self.dst(dt)

    def dst(self, dt):
        d = datetime.datetime(dt.year, 3, 8)        #2nd Sunday in March
        self.dston = d + datetime.timedelta(days=6-d.weekday())
        d = datetime.datetime(dt.year, 11, 1)       #1st Sunday in Nov
        self.dstoff = d + datetime.timedelta(days=6-d.weekday())
        if self.dston <= dt.replace(tzinfo=None) < self.dstoff:
            return datetime.timedelta(hours=1)
        else:
            return datetime.timedelta(0)

    def tzname(self, dt):
        return 'EST5EDT'

dt = datetime.datetime.now(tz=EST5EDT())

Here you are using the abstract base class datetime.tzinfo to create a EST5EDT class which describes what it means to be "Eastern Time Zone", namely your UTC offset (-5 hours) and when daylight savings time is in effect (btwn the 2nd Sunday of March and the 1st Sunday of November).

Btw the template above is pulled from the datetime docs: http://docs.python.org/library/datetime.html

Not sure what you mean "get Python to display the time in eastern", but using the dt object from the last line above:

    In [15]: print(dt)
2012-07-29 12:28:59.125975-04:00

    In [16]: print(dt.strftime('%Y-%m-%d %H:%M:%S'))
2012-07-29 12:28:59

    In [17]: print(dt.strftime('%H:%M:%S'))
12:28:59

    In [18]: print(dt.strftime('%s.%f'))  
1343579339.125975
gnr
  • 2,324
  • 1
  • 22
  • 24
6

Pytz library should be useful. Using Pytz (supports > 2.3) below code can get you the time according to eastern timezone.

from datetime import datetime, timedelta
from pytz import timezone

eastern = timezone('US/Eastern')
fmt = '%Y-%m-%d %H:%M:%S %Z%z'
loc_dt = eastern.localize(datetime(2012, 10, 29, 6, 0, 0))
print loc_dt.strftime(fmt)
Community
  • 1
  • 1
Vinayak Kolagi
  • 1,831
  • 1
  • 13
  • 26
  • I can't seem to install pytz, it's telling me to install via the command line but I have no idea how. I tried what the readme said: c:\python32\python.exe setup.py install. But it said invalid. – Hyzenthlay Jul 29 '12 at 22:16
  • You may have a wrong version of pytz installed. Can you try using "easy_install --upgrade pytz" command. You should have setuptools installed for this. – Vinayak Kolagi Jul 30 '12 at 05:54
  • I don't think setuptools is for Python 3, I can only find versions for Python 2.x. – Hyzenthlay Jul 31 '12 at 01:51
  • [link]http://pypi.python.org/pypi/distribute You can use distribute in python 3 for setuptools. – Vinayak Kolagi Jul 31 '12 at 05:30
2

If for some reason you can't use pytz module and need simple solution then you can use

from datetime import datetime, timezone

datetime.now(timezone(timedelta(hours=-5), 'EST'))
shrishinde
  • 3,219
  • 1
  • 20
  • 31
  • As someone else pointed out, this won't account for daylight savings. – T3metrics Jan 29 '22 at 01:05
  • @1I1III1 the reason for "extra bloatware" is that it takes care of all the edge cases for you, hand crafted solutions such as this one tend to fail randomly. And as mentioned in the comment above me this does not take care of daylight saving... – A Kareem Nov 06 '22 at 02:16
  • @AKareem yeah, you're right. It's kind of funny that this answer and [the one below](https://stackoverflow.com/a/40163812/3476782) have different time deltas because they were posted at different times of year. For context, this solution worked for me because I just needed it for a REPL input rather than a real system. I know I said bloatware, but I think I was actually frustrated with a `left-pad` type package mentality, where even one line solutions get turned into a (sometimes obscure) package import. I guess it isn't always the mistake I thought it was. – 1I1III1 Nov 08 '22 at 09:32
-1

If you need the entire timestamp:

import datetime
print (datetime.datetime.utcnow() - datetime.timedelta(hours=4))

If you just need the date in YYYYmmdd format

print (datetime.datetime.utcnow() - datetime.timedelta(hours=4)).strftime('%Y%m%d')
  • 6
    This incorrectly assumes that the eastern time zone is always offset from UTC by 4 hours. – Tim Oct 20 '16 at 20:42