0

Trying to convert a string to datetime:

from datetime import datetime

date_string = "2021-07-07T02:27:00Z"

datetime.strptime('2021-07-07T02:27:00Z', '%Y-%M-%d %H:%M:%S')


Error:
error: redefinition of group name 'M' as group 5; was group 2 at position 107

Any then I tried:

datetime.fromisoformat(date_string)

Still not working.

Any friend can help?

William
  • 3,724
  • 9
  • 43
  • 76

1 Answers1

2

Your format string is incorrect.


>>> datetime.strptime(date_string, '%Y-%m-%dT%H:%M:%S%z')
datetime.datetime(2021, 7, 7, 2, 27, tzinfo=datetime.timezone.utc)
A.J. Uppal
  • 19,117
  • 6
  • 45
  • 76
  • Z (= UTC) should not be ignored by using a literal Z in the parsing directive. Why? Because it gives you naive datetime, which Python treats as *local time*, which is most likely *not* UTC. You can use `%z` in the directive. See also the dupe question I linked. – FObersteiner Nov 12 '21 at 06:35
  • @MrFuppes edited, thanks! – A.J. Uppal Nov 12 '21 at 19:50