datetime到Unix时间戳,精度为毫秒 [英] datetime to Unix timestamp with millisecond precision

查看:1100
本文介绍了datetime到Unix时间戳,精度为毫秒的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试做一些非常简单的事情,将一个 datetime 对象在未来三天转换为Unix UTC时间戳记:

I'm trying to do something really simple, convert a datetime object three days into the future into a Unix UTC timestamp:

import datetime, time
then = datetime.datetime.now() + datetime.timedelta(days=3)
# Method 1
print then.strftime("%s")
# Method 2
print time.mktime(then.timetuple())
# Method 3 
print time.mktime(then.timetuple()) * 1000

方法1和2给我的Unix时间在,而不是毫秒,方法3给出毫秒,毫秒毫秒毫秒。

Method 1 and 2 give me Unix time in seconds, not milliseconds, and method 3 gives me milliseconds with no actual millisecond precision.

当我打印然后时,我得到 datetime.datetime(2011, 19,15,16,8,278271),所以我知道精度可用于毫秒。如何获取实际毫秒精度的Unix时间戳?如果它作为一个浮点数返回,我必须将它压缩到一个 int ,没关系。有没有解决方案我在寻找这样做?

When I simply print then, I get datetime.datetime(2011, 11, 19, 15, 16, 8, 278271), so I know that the precision is available for milliseconds. How can I get a Unix timestamp with actual millisecond precision? If it's returned as a float and I have to flatten it to an an int, that's fine. Is there a solution I'm looking for that does this?

推荐答案

日期时间对象有一个名为 microsecond 的字段。所以实现你所需要的一种方法是:

Datetime objects have a field named microsecond. So one way to achieve what you need is:

time.mktime(then.timetuple())*1e3 + then.microsecond/1e3

从UNIX时代起,以所需精度返回毫秒。

This returns milliseconds since UNIX epoch with the required precision.

这篇关于datetime到Unix时间戳,精度为毫秒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆