UNIX timestamp from a datetime class

Tim Peters tim.peters at gmail.com
Tue Dec 6 23:13:02 CET 2005


[John Reese]
> >>> import time, calendar, datetime
> >>> n= 1133893540.874922
> >>> datetime.datetime.fromtimestamp(n)
> datetime.datetime(2005, 12, 6, 10, 25, 40, 874922)
> >>> lt= _
> >>> datetime.datetime.utcfromtimestamp(n)
> datetime.datetime(2005, 12, 6, 18, 25, 40, 874922)
> >>> gmt= _
>
> So it's easy to create datetime objects from so-called UNIX timestamps
> (i.e. seconds since Jan 1, 1970 UTC).  Is there any way to get a UNIX
> timestamp back from a datetime object besides the following
> circumlocutions?
>
> >>> float(lt.strftime('%s'))
> 1133893540.0
> >>> calendar.timegm(gmt.timetuple())
> 1133893540

Do

    time.mktime(some_datetime_object.timetuple())

Note that datetime spans a much larger range than most "so-called UNIX
timestamp" implementations, so this conversion isn't actually possible
for most datetime values; e.g.,

>>> time.mktime(datetime(4000, 12, 12).timetuple())
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
OverflowError: mktime argument out of range

on a Windows box.  Note too that Python timestamps extend most UNIXy
ones by being floats with fractional seconds; time,mktime() doesn't
know anything about fractional seconds, and neither does
datetime.timetuple(); e.g.,

>>> time.mktime(datetime.utcfromtimestamp(1133893540.874922).timetuple())
1133911540.0

loses the fractional part.  You can add that back in if you like:

you can add that back in if you like:

    time.mktime(some_datetime_object.timetuple()) + \
        some.datetime_object.microsecond / 1e6



More information about the Python-list mailing list