eg:

>>> print dt
2012-12-04 19:00:00-05:00

As you can see, I have this datetime object How can I convert this datetime object to epoch seconds in GMT -5.

How do I do this?

有帮助吗?

解决方案

Your datetime is not a naive datetime, it knows about the timezone it's in (your print states that is -5). So you just need to set it as utc before you convert it to epoch

>>> import time, pytz
>>> utc = pytz.timezone('UTC')
>>> utc_dt = utc.normalize(dt.astimezone(utc))
>>> time.mktime(utc_dt.timetuple())
1355270789.0 # This is just to show the format it outputs

If the dt object was a naive datetime object, you'd need to work with time zones to comply to daylight saving time while finding the correct hours between GMT 0. For example, Romania in the winter, it has +2 and in the summer +3.

For your -5 example, New-York will do:

>>> import time,pytz
>>> timezone = pytz.timezone('America/New_York')
>>> local_dt = timezone.localize(dt)

Now you have a non-naive datetime and you can get the epoch time like I first explained. Have fun

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top