Please help me to change datetime object (for example: 2011-12-17 11:31:00-05:00
) (including timezone) to Unix timestamp (like function time.time() in Python).
Asked
Active
Viewed 5.3k times
22

Jonathan Leffler
- 730,956
- 141
- 904
- 1,278

Thelinh Truong
- 564
- 1
- 8
- 19
-
Possibly a duplicate of http://stackoverflow.com/questions/2775864/python-datetime-to-unix-timestamp – Felix Yan Dec 18 '11 at 04:08
-
related: [Converting datetime.date to UTC timestamp in Python](http://stackoverflow.com/a/8778548/4279) – jfs May 26 '13 at 01:40
3 Answers
14
Another way is:
import calendar
from datetime import datetime
d = datetime.utcnow()
timestamp=calendar.timegm(d.utctimetuple())
Timestamp is the unix timestamp which shows the same date with datetime object d.

coffee-grinder
- 26,940
- 19
- 56
- 82

Shnkc
- 2,108
- 1
- 27
- 35
-
4note: it removes fractions of a second. To preserve microseconds, use: [`(d - datetime(1970,1,1)).total_seconds()`](http://stackoverflow.com/a/8778548/4279) – jfs Dec 30 '14 at 09:48
13
import time
import datetime
dtime = datetime.datetime.now()
ans_time = time.mktime(dtime.timetuple())

user2673780
- 131
- 1
- 4
-
2Local time may be ambiguous e.g., during end-of-DST transitions ("fall back"). `timetuple()` sets `tm_isdst` to `-1` that forces `mktime()` to guess i.e., there is 50% chance it gets it wrong. Either use utc time or aware datetime objects. – jfs Dec 30 '14 at 09:46
6
Incomplete answer (doesn't deal with timezones), but hopefully useful:
time.mktime(datetime_object.timetuple())
** Edited based on the following comment **
In my program, user enter datetime, select timezone. ... I created a timezone list (use pytz.all_timezones) and allow user to chose one timezone from that list.
Pytz module provides the necessary conversions. E.g. if dt
is your datetime
object, and user selected 'US/Eastern'
import pytz, calendar
tz = pytz.timezone('US/Eastern')
utc_dt = tz.localize(dt, is_dst=True).astimezone(pytz.utc)
print calendar.timegm(utc_dt.timetuple())
The argument is_dst=True
is to resolve ambiguous times during the 1-hour intervals at the end of daylight savings (see here http://pytz.sourceforge.net/#problems-with-localtime).

DS.
- 22,632
- 6
- 47
- 54
-
-
Does the input datetime object contain a proper tzinfo? Or, if not, how do you know which timezone you are interested in? – DS. Dec 17 '11 at 05:40
-
1yes. In my program, user enter datetime, select timezone. I use python language, I created a timezone list ( use pytz.all_timezones ) and allow user to chose one timezone from that list. My problem is how to convert the datetime along with timezone id to unix timestamp. All above answer donot solve my problem. Please help me. – Thelinh Truong Dec 19 '11 at 04:02