Python Datetime 将所有值合并为 int

Python Datetime Merging all values into int

我想把程序的日期时间转换成int,我想要的是:

import datetime
print(datetime.datetime.utcnow())

> 2021-01-12 09:15:16.9791000 # the time I ran the command

进入这个:

> 202101120915169791000

我该怎么做?

使用strftime格式。

import datetime
a = datetime.datetime.utcnow()
a = int(a.strftime('%Y%m%d%H%M%S'))
print(a)

# Output
# 20210112092900

如果你想获得整个纳秒,那就试试吧

print(int(a.strftime('%Y%m%d%H%M%S%f')))
# Output
#20210112092900275246

您可以使用索引或 运行 通过它作为字符串。

import datetime
s = str(datetime.datetime.utcnow())
chars_list = ['-', ' ', ':', '.']
ans = ''
for c in s:
    if c not in chars_list:
        ans = ans + c
print(int(ans))