5

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?

Sagar Hatekar
  • 8,700
  • 14
  • 56
  • 72

1 Answers1

6

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

mihaicc
  • 3,034
  • 1
  • 24
  • 20
  • 1
    Presumably the "-05:00" already codes the proper offset for the given date and time zone, so why go to the trouble of working backwards? – Mark Ransom Dec 11 '12 at 23:59
  • Thank you, I missed the -5 in the print. I adapted the answer to explain how to convert from non-naive datetime aswell. – mihaicc Dec 12 '12 at 00:29