UNIX timestamp from a datetime class

J

John Reese

Hi.

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?
1133893540
 
G

gry

John said:
Hi.


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?
1133893540.874922
 
T

Tim Peters

[John Reese]
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?

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.,
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.,
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,043
Latest member
CannalabsCBDReview

Latest Threads

Top