python - 有什么快速方法来获取时间并将其转换为时间戳吗?

标签 python python-3.x python-2.7 amazon-web-services boto3

有什么快速方法来获取时间并将其转换为时间戳吗?

string="2018-10-17 12:31:46 UTC::@:[2771]:LOG: checkpoint starting: time"

我可以使用split来获取前4个

>>> string.split(":")[:3]
['2018-10-17 12', '31', '46 UTC']

但是如何将它们合并回时间字符串并转换为时间戳?

更新

@jezrael使用你的解决方案,我将其转换为时间戳,但似乎时间发生了漂移。

>>> date = parser.parse(':'.join(string.split(":")[:3]))
>>> print(date)
2018-10-17 12:31:46+00:00
>>> timestamp = int(round(time.mktime(date.timetuple()) * 1000))
>>> print(timestamp)
1539743506000

我使用下面的代码将日志上传到cloudwatch,它使用了我从日志字符串中获取的日期/时间戳。

 logs = boto3.client('logs')

 date = parser.parse(':'.join(string.split(":")[:3]))
 timestamp = int(round(time.mktime(date.timetuple()) * 1000))
 event_response = logs.put_log_events(
    logGroupName=LOG_GROUP,
    logStreamName=LOG_STREAM,
    logEvents=[{
        'timestamp': timestamp,
        'message': string
    }],
    sequenceToken=str(next_sequence_token))

coudwatch 中的真实日志日期不同:

enter image description here

更新#2

最后我用下面的代码做了,它需要 python v3.3+

$ python3
Python 3.7.0 (default, Oct  4 2018, 14:10:21)
[Clang 10.0.0 (clang-1000.10.44.2)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from dateutil import parser
>>> string="2018-10-17 12:31:46 UTC::@:[2771]:LOG: checkpoint starting: time"
>>> date = parser.parse(':'.join(string.split(":")[:3]))
>>> timestamp = int(round(date.timestamp() * 1000))
>>> print(timestamp)
1539779506000

最佳答案

我们可以将 joinparser 模块一起使用。

from dateutil import parser

string="2018-10-17 12:31:46 UTC::@:[2771]:LOG: checkpoint starting: time"

date = parser.parse(':'.join(string.split(":")[:3]))
print (date)
2018-10-17 12:31:46+00:00

关于python - 有什么快速方法来获取时间并将其转换为时间戳吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52867856/

相关文章:

Python部署和/usr/bin/env可移植性

python - python 脚本的输出读入 C 程序,无需创建临时文件以在程序之间传递值

python - 如何使用重复键合并多个字典中的数据?

python - Pandas :不能删除列:ValueError:标签 [<colName>] 不包含在轴中

python - 如何让 Luigi 任务自行关闭?

Python Tkinter : multiple images and text on a BIG button?

python - 在 Django 1.8 中手动提交

python - 加权平均,其中一个权重是无限的

python - 自动 sklearn : How to load pickle file and run predict()

Python 3 的 OAuth 端口