datetime to timestamp

S

Simen Haugen

Hi.

How can I convert a python datetime to a timestamp? It's easy to convert
a timestamp to datetime (datetime.datetime.fromtimestamp(), but the
other way around...?)

-Simen
 
J

John Machin

Hi.

How can I convert a python datetime to a timestamp? It's easy to convert
a timestamp to datetime (datetime.datetime.fromtimestamp(), but the
other way around...?)

-Simen

Is the timetuple() method what you want?

#>>> import datetime
#>>> n = datetime.datetime.now()
#>>> n
datetime.datetime(2006, 8, 11, 23, 32, 43, 109000)
#>>> n.timetuple()
(2006, 8, 11, 23, 32, 43, 4, 223, -1)

Cheers,
John
 
J

John Machin

Is the timetuple() method what you want?

#>>> import datetime
#>>> n = datetime.datetime.now()
#>>> n
datetime.datetime(2006, 8, 11, 23, 32, 43, 109000)
#>>> n.timetuple()
(2006, 8, 11, 23, 32, 43, 4, 223, -1)


Aaaarrrggghhh no it's not what you want -- looks like you have to do the
arithmetic yourself, starting with toordinal()
 
S

Sion Arrowsmith

John Machin said:
Is the timetuple() method what you want?
[ ... ]
Aaaarrrggghhh no it's not what you want -- [ ... ]

It is if you only want it to the second. It just needs a time.mktime():
1155307613.0

(timetuple() is responsible for the loss of the fractional part.)
 
T

Tim Peters

[Simen Haugen]
[John Machin]
[also John]
Aaaarrrggghhh no it's not what you want

Yes, it is ;-)
-- looks like you have to do the arithmetic yourself, starting with toordinal()

It's just one step from the time tuple:

import time
time.mktime(some_datetime_object.timetuple())

The datetime module intended to be an island of relative sanity.
Because the range of dates "timestamps" can represent varies across
platforms (and even "the epoch" varies), datetime doesn't even try to
produce timestamps directly -- datetime is more of an alternative to
"seconds from the epoch" schemes. Because datetime objects have
greater range and precision than timestamps, conversion is
problem-free in only one direction. It's not a coincidence that
that's the only direction datetime supplies ;-)
 
J

John Machin

Tim said:
[Simen Haugen]
[John Machin]
[also John]
Aaaarrrggghhh no it's not what you want

Yes, it is ;-)
-- looks like you have to do the arithmetic yourself, starting with toordinal()

It's just one step from the time tuple:

import time
time.mktime(some_datetime_object.timetuple())

Thanks, Tim. In mitigation, yer honour, I'd like to draw your attention
to the local time (23:32); the defendant was rushing to do the OP's
RTFantasticM for him before retiring for the night, and not doing it
well enough :)
Cheers,
John
 

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

Forum statistics

Threads
473,774
Messages
2,569,598
Members
45,151
Latest member
JaclynMarl
Top