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.
Thanks.
解决方案
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