0

I'm trying to parse a string as a datetime, put it as a new timezone (CEST UTC+02) and return it, but I get this error:

> ValueError: time data '2022-07-04T03:15:00Z' does not match format '%Y-%m-%dT%H:%M:%S.%f%z'

Example input:

2022-07-04T03:15:00Z
2022-07-04T12:40:20Z
2022-07-04T11:56:08Z

Example output:

2022-07-04T05:15:00+02:00
2022-07-04T14:40:20+02:00
2022-07-04T13:56:08+02:00

Code:

from datetime import timedelta, datetime

str = "2022-07-04T03:15:00Z"
str = (datetime.strptime(str, '%Y-%m-%dT%H:%M:%S.%f%z') + timedelta(hours=2)).isoformat()
print(str)

I also tried:

str = (datetime.strptime(str, '%Y-%m-%dT%H:%M:%S.000%z') + timedelta(hours=2)).isoformat()

and:

str = (datetime.strptime(str, '%Y-%m-%dT%H:%M:%S.%fz') + timedelta(hours=2)).isoformat()

as suggested by this and by this:

Deutrys
  • 15
  • 5
  • Try with `"2022-07-04T03:15:00.000Z"` – Hackerman Jul 04 '22 at 20:49
  • Dupe of [How do I parse an ISO 8601-formatted date](https://stackoverflow.com/questions/127803/how-do-i-parse-an-iso-8601-formatted-date) - also, you might want to have a look at [Display the time in a different time zone](https://stackoverflow.com/questions/1398674/display-the-time-in-a-different-time-zone). – FObersteiner Jul 05 '22 at 04:39

1 Answers1

1

Your format is incorrect, remove the .%f, you have no microseconds:

from datetime import timedelta, datetime

s = "2022-07-04T03:15:00Z"
s = (datetime.strptime(s, '%Y-%m-%dT%H:%M:%S%z') + timedelta(hours=2)).isoformat()
print(s)

Output: 2022-07-04T05:15:00+00:00

alper
  • 2,919
  • 9
  • 53
  • 102
mozway
  • 194,879
  • 13
  • 39
  • 75
  • "*Output: 2022-07-04T05:15:00+00:00*" - shouldn't that be +02:00 ? ;-) Maybe suggest how to handle time zones / UTC offsets properly, see comment under the question – FObersteiner Jul 05 '22 at 04:43