UNIX timestamp from a datetime class

gry at ll.mit.edu gry at ll.mit.edu
Tue Dec 6 22:53:37 CET 2005


John Reese wrote:
> Hi.
>
> >>> 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?

>>> d=datetime.datetime.fromtimestamp(1133893540.874922)
>>> epoch = int(d.strftime('%s'))
>>> usec = d.microsecond
>>> epoch + (usec / 1000000.0)
1133893540.874922




More information about the Python-list mailing list