Brandon Nadeau
Brandon Nadeau

Reputation: 3706

Python - Converting string to datetime object

I've been trying to convert a timestamp that is a string to a datetime object. The problem is the timestamps formatting. I haven't been able to properly parse the timestamp using datetime.datetime.strptime. I could write my own little parser as its a simple problem but I was hoping to use strptime function, I just need help on the formatting.

Example

import datetime

formater = "%y-%m-%dT%H:%M:%SZ"
str_timestamp = "2021-03-13T18:27:37.60918Z"
timestamp = datetime.datetime.strptime(str_timestamp, formater)

print (timestamp)

Output

builtins.ValueError: time data '2021-03-13T18:27:37.60918Z' does not match format '%y-%m-%dT%H:%M:%SZ'

I'm clearly not symbolizing the formatter properly, the T and Z parts are what I can't account for.

Upvotes: 0

Views: 3433

Answers (2)

Vedank Pande
Vedank Pande

Reputation: 446

This format works:

formater = "%Y-%m-%dT%H:%M:%S.%fZ"

output:

2021-03-13 18:27:37.609180

Upvotes: 0

DeepSpace
DeepSpace

Reputation: 81594

  • y should be Y. y is for 2 digits year.

  • You should also take care for the milliseconds with .%f:


%Y-%m-%dT%H:%M:%S.%fZ

Upvotes: 2

Related Questions