Home > Enterprise >  How to convert a date string zone oriented and hour string into datetime
How to convert a date string zone oriented and hour string into datetime

Time:02-16

I have two strings one: date='2021-12-30T23:00Z' where Z means UTC timezone and 23:00 means hour. I also have an hour string hour='3'. What I want is to convert date to datetime object and add this hour string to date as a delta. In result I would get a datetime object with hour: '2021-12-31T02:00Z' I tried function datetime.datetime.fromisoformat() with no luck.

CodePudding user response:

You could do something like this:

from datetime import datetime
from datetime import timedelta


date = "2021-12-30T23:00Z"
hour = "3"

d = datetime.strptime(date, "%Y-%m-%dT%H:%M%z")   timedelta(hours=int(hour))
print(d)

output:

2021-12-31 02:00:00 00:00

CodePudding user response:

Use strftime with their format.

from datetime import datetime, timedelta
date='2021-12-30T23:00Z'

date = datetime.strptime(date, '%Y-%m-%dT%H:%MZ')
new_date = date   timedelta(hours=3)
new_date = new_date.strftime('%Y-%m-%dT%H:%MZ')
print(new_date)

Output:

2021-12-31T02:00Z

  • Related