Python DateTime 字符串转换为整数毫秒

SMG*_*eld 2 python mysql datetime datetime-format python-2.7

我想将 UTC TimeDate 标记字符串转换为毫秒的整数值(可能需要是 64 位数量),以便在存储在 mySQL 数据库列中时占用更少的空间。这个 UTC 字符串是从另一个库生成的,我将它存储为一种每用户 GUID。

datetime 或 dateutil 能否将其转换为单个整数值(例如“自纪元以来的毫秒数”)?还是我需要自己做?

使用这种方法解析:

myDateTime = dateutil.parser.parse("2015-06-27T02:10:05.653000Z")
print("Parsed datetime String is {0}, ordinal value is {1}".format(myDateTime, myDateTime.toordinal()))
Run Code Online (Sandbox Code Playgroud)

给出输出:

Parsed datetime String is 2015-06-27 02:10:05.652999+00:00, ordinal value is 735776
Run Code Online (Sandbox Code Playgroud)

...它只给出日期的序数值。此外,如果我有一个整数 653 毫秒的时间,那么我希望解析的对象知道它有 653 毫秒,而不是 652999。

Sco*_*ott 5

[在评论中编辑了以下建议]

使用Ben AlpertHow can I convert a datetime object to milliseconds since epoch (unix time) in Python in Python回答,我们可以执行以下操作:

from datetime import datetime
def unix_time(dt):
    epoch = datetime.utcfromtimestamp(0)
    delta = dt - epoch
    return delta.total_seconds()

def unix_time_millis(dt):
    return int(unix_time(dt) * 1000)

a = datetime.strptime("2015-06-27T02:10:05.653000Z", "%Y-%m-%dT%H:%M:%S.%fZ")
unix_time_millis(a)
Run Code Online (Sandbox Code Playgroud)

返回:

1435371005653
Run Code Online (Sandbox Code Playgroud)

相当于:Sat, 27 Jun 2015 02:10:05 GMT(如预期)

我们还可以使用 datetime's.strftime('%s')来获取 unix 时间,甚至是毫秒,使用以下方法(但不建议这样做):

from decimal import Decimal

int(Decimal(datetime.strptime("2015-06-27T02:10:05.653000Z", "%Y-%m-%dT%H:%M:%S.%fZ").strftime('%s.%f'))*1000)
Run Code Online (Sandbox Code Playgroud)

返回:

1435396205653
Run Code Online (Sandbox Code Playgroud)

相当于:2015 年 6 月 27 日星期六 09:10:05 GMT(在我在圣地亚哥的 Mac 上;注意:这比我们预期的要7 小时)。

JF Sebastian 在上面链接的评论和关于.strftime('%s')行为的答案中描述了错误的原因。JF Sebastian 指出“它不受支持,不可移植,它可能会默默地为已知的日期时间对象产生错误的结果,如果输入为 UTC(如问题中所示)但本地时区不是 UTC,则它会失败”