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?

Rosso
  • 93
  • 2
  • 9

3 Answers3

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.

smci
  • 32,567
  • 20
  • 113
  • 146
  • 1
    The timestamp is an iso formatted string, any format specifiers would be redundant when you can just call 'fromisoformat' – Boskosnitch Feb 16 '21 at 02:57
  • @Boskosnitch: oh ok, didn't know ISO included microseconds. Is it guaranteed to handle all timezone specifiers? – smci Feb 16 '21 at 06:52
  • 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" – Rosso Feb 16 '21 at 18:08
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)))
Boskosnitch
  • 774
  • 3
  • 8
  • 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 :) – Rosso Feb 16 '21 at 09:02
  • 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" – Rosso Feb 16 '21 at 14:24
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

Rosso
  • 93
  • 2
  • 9