简体   繁体   English

如何将毫秒的时间戳转换为日期时间?

[英]How to convert timestamp with milliseconds into datetime?

I am using Google Drive API to download some files but unable to convert its datetime into Python datetime:我正在使用 Google Drive API 下载一些文件,但无法将其日期时间转换为 Python 日期时间:

 '2022-04-23T15:38:11.588Z' does not match format '%Y-%m-%dT%H:%M:%SZ'

I thought this would work:我认为这会起作用:

 datetime.strptime(meta["modifiedTime"], '%Y-%m-%dT%H:%M:%SZ'))

How can I do this?我怎样才能做到这一点?

All but the final letter Z is isoformat, so we can just do:除了最后一个字母Z之外的所有字母都是 isoformat,所以我们可以这样做:

 from datetime import datetime d = '2022-04-23T15:38:11.588Z' print(datetime.fromisoformat(d[:-1]))

Output: Output:

 2022-04-23 15:38:11.588000

Alternative:选择:

 from dateutil.parser import isoparse print(isoparse(d)) # Output: 2022-04-23 15:38:11.588000+00:00

Because the seconds you are getting from the Google Drive API time, is in float type format.因为您从 Google Drive API 时间获得的秒数是浮点型格式。 So instead of just doing %SZ , you can specify %S.%fZ that will now read the seconds in float.因此,您可以指定%S.%fZ ,而不是仅仅执行%SZ ,它现在将读取浮点数中的秒数。

 from datetime import datetime date = '2022-04-23T15:38:11.588Z' print(datetime.strptime(date, '%Y-%m-%dT%H:%M:%S.%fZ'))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM