Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert datetime object in a particular timezone to epoch seconds in that timezone

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?

like image 791
Sagar Hatekar Avatar asked Dec 11 '12 23:12

Sagar Hatekar


1 Answers

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

like image 120
mihaicc Avatar answered Sep 30 '22 11:09

mihaicc