0

I tried this:

 timestamp = "2021-01-22T11:36:52.387000+01:00"
 timestampObject = datetime.strptime(timestamp, '%Y-%m-%dT%H:%M:%S')

But gave me error:

ValueError: unconverted data remains: .150000+01:00

What is the rest reprisenting and how do I convert the rest? Also what does the 'T' mean?

3 Answers 3

1

Because you also have to supply a format specifier to take care of the trailing microseconds and timezone specifier, like the error is telling you, see Conversion of datetime string with microseconds and ...milliseconds. Probably you need '.fZ'. See the datetime doc.

Also, the 'T' just stands for 'Time'; it separates the date-field from the time-field, for ease in parsing (with sed/perl/grep/regex/etc.). Makes it easy if you wanted to a) locate datetimes within a log or b) throw away/separate the time part from the date part.

Sign up to request clarification or add additional context in comments.

3 Comments

The timestamp is an iso formatted string, any format specifiers would be redundant when you can just call 'fromisoformat'
@Boskosnitch: oh ok, didn't know ISO included microseconds. Is it guaranteed to handle all timezone specifiers?
whats the differene with this format 2018-04-19T00:00:00+02:00 and the other one? datetime.fromisoformat does not work on this fromat. It says "argument must be str"
1

The string format you have is actually a datetime in ISO format. Luckily datetime has a function for handling that, you don't have to worry about supplying a format specifier for the trailing time objects...

Do you want only the date?

>>> datetime.datetime.fromisoformat("2021-01-22T11:36:52.387000+01:00").date()
datetime.date(2021, 1, 22)

Or do you want datetime?

>>> datetime.datetime.fromisoformat("2021-01-22T11:36:52.387000+01:00")
datetime.datetime(2021, 1, 22, 11, 36, 52, 387000, tzinfo=datetime.timezone(datetime.timedelta(seconds=3600)))

2 Comments

Thanks, but It worked only when I removed the first datetime. I dont know if that was a typo or if its because i am using python3, but thanks for help :)
whats the differene with this format 2018-04-19T00:00:00+02:00 and the other one? datetime.fromisoformat does not work on this fromat. It says "argument must be str"
0

This worked for me:

timestampObject = datetime.fromisoformat(
 "2021-01-22T11:36:52.387000+01:00" ).date()

 print('timestampObject.year: ', timestampObject.year) 

timestampObject.year: 2021

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.