In Python, how do you convert a `datetime` object to seconds?
为这个简单的问题道歉…我是Python的新手…我到处找过,好像什么都没用。
我有很多datetime对象,我想为每个对象计算自过去固定时间以来的秒数(例如,从1970年1月1日起)。
1 2 | import datetime t = datetime.datetime(2009, 10, 21, 0, 0) |
这似乎只是区分不同日期:
1 | t.toordinal() |
任何帮助都非常感谢。
For the special date of January 1,1970 there are multiple options.
对于任何其他的起始日期,你需要区分两个日期在第二个日期。二次跟踪两个日期给出一个
1 2 | >>> (t-datetime.datetime(1970,1,1)).total_seconds() 1256083200.0 |
起始日期通常是在UTC中具体规定的,因此,为了推荐
如评注所述,如果你有一个
To get the Unix Time(Seconds since January 1,1970):
1 2 3 4 | >>> import datetime, time >>> t = datetime.datetime(2011, 10, 21, 0, 0) >>> time.mktime(t.timetuple()) 1319148000.0 |
从Python3.3开始,这个方法变得非常容易。如果您需要从1970-01-01 UTC的第二个数字,这一课程只能使用。
1 2 3 | from datetime import datetime dt = datetime.today() # Get timezone naive now seconds = dt.timestamp() |
返回值将是一个浮点,甚至是一个第二部分。如果Datetime is timezone naive(as in the example above),it will be assumed that the datetime object represents the local time,I.E.It will be the number of seconds from current time at your location to 1970-01-01 UTC.
同样的工作
Maybe off-the-topic:to get UNIX/posix time from datetime and convert it back:
1 2 3 4 5 6 7 8 9 | >>> import datetime, time >>> dt = datetime.datetime(2011, 10, 21, 0, 0) >>> s = time.mktime(dt.timetuple()) >>> s 1319148000.0 # and back >>> datetime.datetime.fromtimestamp(s) datetime.datetime(2011, 10, 21, 0, 0) |
Note that different times zones have impact on results,e.g.My current TZ/DST returns:
1 2 | >>> time.mktime(datetime.datetime(1970, 1, 1, 0, 0).timetuple()) -3600 # -1h |
因此,应当考虑使用UTC版本的功能规范UTC。
注:先前的结果可用于计算当前时区的UTC偏移。In this example this is+1H,I.E.UTC+0100.
参考资料:
- 日期
- 时间
- DateIme.DateIme.FromTimestamp
- 时间模块解释时间,1970年EPOCH,UTC,TZ,DST…
From the Python Docs:
1 | timedelta.total_seconds() |
Return the total number of seconds contained in the duration.相当于
ZZU1
Computed with true division enabled.
注:对于极大的时间间隔(在最多平台上超过270年),这一方法将失去微秒精度。
This functionality is new in version 2.7.
To convert a datetime object that represents time in UTC to posix timestamp:
1 2 3 | from datetime import timezone seconds_since_epoch = utc_time.replace(tzinfo=timezone.utc).timestamp() |
To convert a datetime object that represents time in the local timezone to posix timestamp:
1 2 3 4 | import tzlocal # $ pip install tzlocal local_timezone = tzlocal.get_localzone() seconds_since_epoch = local_timezone.localize(local_time, is_dst=None).timestamp() |
看看我怎么在Python里跟UTC聊天?如果TZ数据库可在一个Given Platform上查阅;STDLIB-Only solution may work.
如果你需要解答的话,跟随链接
我尝试标准图书馆的日历.时间,它的工作结束了:
1 2 3 | # convert a datetime to milliseconds since Epoch def datetime_to_utc_milliseconds(aDateTime): return int(calendar.timegm(aDateTime.timetuple())*1000) |
Ref:https://docs.python.org/2/library/calendar.html 350;calendar.timegm