Home > front end >  Timezone in python date string is not matching
Timezone in python date string is not matching

Time:06-06

In a script, I am converting the date string into DateTime format, so that I can modify the date, but this timezone part is showing an error.

from datetime import datetime
date_str = 'Wed, 1 Jun 2022 16:44:40  0200 (CEST)'

temp_date = datetime.strptime(date_str, '%a, %d %b %Y %H:%M:%S %z (%Z)')
print(temp_date)

When I run this I am getting ValueEror.

ValueError: time data 'Wed, 01 Jun 2022 16:44:40  0200 (CEST)' does not match format '%a, %d %b %Y %H:%M:%S %z (%Z)'

CodePudding user response:

An extract from the datetime documentation:

strptime() only accepts certain values for %Z:

any value in time.tzname for your machine’s locale

the hard-coded values UTC and GMT

So someone living in Japan may have JST, UTC, and GMT as valid values, but probably not EST. It will raise ValueError for invalid values

Try running the below to see if CEST is in your machine's locale:

import time
print(time.tzname)

CodePudding user response:

Seeing the complexity of problem, I suggest using third party library like dateutil which can parse datetime with ease.

from dateutil.parser import parse
date_str = 'Wed, 1 Jun 2022 16:44:40  0200 (CEST)'
temp_date = parse(date_str)
print(temp_date)

temp_date is of type datetime.datetime

https://dateutil.readthedocs.io/en/stable/

  • Related