在Python中,如何将datetime对象转换为epoch(unix time)之后的毫秒数?

2024-04-18 08:17:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个Pythondatetime对象,我想将其转换为unix时间,或者自1970年以来的秒/毫秒。

我该怎么做?


Tags: 对象时间unixpythondatetime
3条回答

在我看来,最简单的方法是

import datetime

epoch = datetime.datetime.utcfromtimestamp(0)

def unix_time_millis(dt):
    return (dt - epoch).total_seconds() * 1000.0

在Python3.3中,添加新方法。

datetime.timestamp()

https://docs.python.org/3.3/library/datetime.html#datetime.datetime.timestamp

>>> import datetime
>>> # replace datetime.datetime.now() with your datetime object
>>> int(datetime.datetime.now().strftime("%s")) * 1000 
1312908481000

或时间模块的帮助(不带日期格式):

>>> import datetime, time
>>> # replace datetime.datetime.now() with your datetime object
>>> time.mktime(datetime.datetime.now().timetuple()) * 1000
1312908681000.0

得到了来自http://pleac.sourceforge.net/pleac_python/datesandtimes.html的帮助

文件:

相关问题 更多 >