Joan Venge
Joan Venge

Reputation: 331410

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:

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

Upvotes: 0

Views: 438

Answers (2)

Asad Hussain
Asad Hussain

Reputation: 229

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

Upvotes: 1

BeRT2me
BeRT2me

Reputation: 13241

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

Upvotes: 1

Related Questions