开发者

Convert date, datetime to timestamp

How can I produce a timestamp to milli开发者_C百科second accuracy from a date or datetime in Python?

There are an overwhelming number of methods and ways of doing this, and I'm wondering which is the most Pythonic way.


The following has worked for my purposes:

To datetime from millisecond timestamp

import datetime
timestamp #=> 1317912250955
dt = datetime.datetime.fromtimestamp(time/1000.0)
dt #=> datetime.datetime(2011, 10, 6, 10, 44, 10, 955000)

From datetime to millisecond timestamp

import time
dt #=> datetime.datetime(2011, 10, 6, 10, 44, 10, 955000)
timestamp = int((time.mktime(dt.timetuple()) + dt.microsecond/1000000.0)*1000)
timestamp #=> 1317912250955


date objects in Python don't preserve the notion of wallclock time. If you wanted to take a date object and get a representation with the millisecond, it would be all 0s.

The datetime module skips milliseconds and supports microseconds in its formatting. So when you print a datetime or see one in the interpreter, that last field is microsecond. If you want milliseconds, you can divide that field by 1000.

Here's a couple of examples from a Python 3.2b2 interpreter session. There's some extra stuff in here so you can see the basic route I took to get to a timestamp. It's not to be considered a substitute for reading the docs:

>>> x = datetime.datetime.today()
>>> y = datetime.date.today()
>>> x
datetime.datetime(2011, 2, 6, 8, 2, 9, 465714)
>>> y
datetime.date(2011, 2, 6)
>>> y.strftime('%Y-%m-%d.%f')
'2011-02-06.000000'
>>> x
datetime.datetime(2011, 2, 6, 8, 2, 9, 465714)
>>> str(x)
'2011-02-06 08:02:09.465714'
>>> x.microsecond
465714
>>> x.time()
datetime.time(8, 2, 9, 465714)
>>> x.time().microsecond/1000
465.714   # milliseconds and microseconds.
>>> int(x.time().microsecond / 1000)
465  # milliseconds
>>> s = '{:02d}:{:02d}:{:02d}.{:3d}'.format(r.hour, r.minute, r.second, int(r.microsecond / 1000), '2s')
>>> s
'08:02:09.465'


What is the most pythonic way depends on what you want when you say "timestamp". A number or a string?

For strings, d.isoformat() is the easiest one. For numbers you do you:

time.mktime(d.timetuple()) + d.microsecond/1000000.0

This is assuming datetime objects. I'm not sure what you mean when you say you want a millisecond accuracy timestamp from date objects. date objects doesn't even have seconds, much less milliseconds. :-)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜