0

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.

3
  • 1
    No, the problem is that the %y should be %Y... Commented Apr 1, 2021 at 21:22
  • 1
    Plus, the %S format doesn't recognize fractional seconds. Commented Apr 1, 2021 at 21:23
  • Does this answer your question? How do I parse an ISO 8601-formatted date? Commented Apr 1, 2021 at 22:44

2 Answers 2

2
  • 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
Sign up to request clarification or add additional context in comments.

4 Comments

Awesome it works. I haven't parsed timestamps in a while. Thanks.
Z denotes UTC, that shouldn't be just ignored by using a literal Z in the strftime directive
Are you saying I should or shouldn't include the Z in the formatter
@Crispy you can replace it with %z - then you should get a datetime object with tzinfo set to UTC. This makes a difference because if tzinfo is not set, Python will treat datetime objects as local time (your OS setting).
0

This format works:

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

output:

2021-03-13 18:27:37.609180

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.