2

I can't figure out the correct second argument of strptime for the following date format

a = datetime.strptime('2017-03-09 14:00:00.000000+0000', '%y-%m-%d %H:%M:%S.%f+%z')

The error I get is:

ValueError: time data '2017-03-09 14:00:00.000000+0000' does not match format '%y-%m-%d %H:%M:%S.%f+%z'

Could anyone help me out?

questionto42
  • 7,175
  • 4
  • 57
  • 90
Lukasz
  • 2,257
  • 3
  • 26
  • 44

3 Answers3

6

The correct format string is:

%Y-%m-%d %H:%M:%S.%f%z

You can figure this out more easily next time by using strftime() to write a datetime using a given format. For example, your original:

datetime.datetime.now().astimezone(tz=None).strftime('%y-%m-%d %H:%M:%S.%f+%z')

gives:

17-03-13 22:53:50.010314++0800

And from there it is fairly easy to see what's wrong.

John Zwinck
  • 239,568
  • 38
  • 324
  • 436
4

This is how it goes:

import datetime

output_date = datetime.datetime.now(tz = datetime.datetime.now().astimezone().tzinfo).isoformat(timespec='milliseconds')

print(output_date)

Gives:

"2021-04-20T16:56:29.800+02:00"

Which is in ISO 8601 yyyy-MM-dd'T'HH:mm:ss.SSSXXX format.

Shady
  • 216
  • 2
  • 6
0

The other answers are fine, it is just that I guess that the question about one example case arose from a full column of a dataframe that needs to be converted to datetime.

Just for those who have a dataframe instead and need to reformat the whole column like me:

pd.to_datetime(df['MY_STR_TIMESTAMP_COLUMN_NAME'])

Taken from Convert DataFrame column type from string to datetime.

If you are lazy and do not mind the overhead of pandas, then you could do this even for just one entry.

questionto42
  • 7,175
  • 4
  • 57
  • 90