Home > Software engineering >  How to convert timestamp with milliseconds into datetime?
How to convert timestamp with milliseconds into datetime?

Time:07-24

I am using Google Drive API to download some files but unable to convert its datetime into Python datetime:

'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?

CodePudding user response:

All but the final letter Z is isoformat, so we can just do:

from datetime import datetime

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

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

CodePudding user response:

Because the seconds you are getting from the Google Drive API time, is in float type format. So instead of just doing %SZ, you can specify %S.%fZ that will now read the seconds in float.

from datetime import datetime

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