user96564
user96564

Reputation: 1607

converting to missing plus sign offset datetime string to proper datetime

Mostly I receive the datetime string in this format d_string = '2019-03-25 15:30:00+00:00' and I can convert to proper datetime by using

date_converted = datetime.strptime(d_string , '%Y-%m-%d %H:%M:%S%z')

But sometime, I receive date string like this '2019-03-25 15:30:00 00:00' where there is no plus sign anymore. How can I validate this type of datestring to proper datetime format ? I could always add the plus sign from the last 4th position in the datestring and do the validation, but this doesn't look a better solution.

Is there a better way ?

Upvotes: 2

Views: 1509

Answers (1)

azro
azro

Reputation: 54148

If you want to use the 00:00 at the end, you may add the + to match the required pattern, this is how you can do it

if re.fullmatch(r"[\d-]{10} [\d:]{8} [\d:]{5}", value):
    value = re.sub(r"(?<=[\d:]{8})( )(?=[\d:]{5})", "+", value)

Giving

values = ['2019-03-25 15:30:00+00:00', '2019-03-25 15:30:00 00:00']
for value in values:
    if re.fullmatch(r"[\d-]{10} [\d:]{8} [\d:]{5}", value):
        value = re.sub(r"(?<=[\d:]{8})( )(?=[\d:]{5})", "+", value)
    date_converted = datetime.strptime(value, '%Y-%m-%d %H:%M:%S%z')
    print(date_converted)

Upvotes: 2

Related Questions