简体   繁体   中英

Unable to parse time in Python

Let's say I have the following string:

timeUTC = "14:28"

And I would like to convert the above string to UTC+2.

So timeUTCp2 = "16:28" .

How can I do that using Python3? Is the quickest way to do this algebraically or using a dependency?

You can 2 hours to UTC like this:

from datetime import datetime, timedelta
from pytz import timezone

time_str = "14:28"
time = datetime.strptime(date_str, "%H:%M")
utc = timezone('UTC').localize(time)

utcp2 = utc + timedelta(hours=2)
'{:%H:%M}'.format(utcp2)

There are two ways, that I can think of:

FIRST, if you want to just add two hours to the string time (that doesn't appear to have a timezone attached to it):

from datetime import datetime
from datetime import timedelta
dt = datetime.strptime("14:28", "%H:%M") + timedelta(hours=2)

SECOND, you could convert from whatever timezone the input string is from to UTC then add two hours. I don't know where that time string is coming from so I didn't construct an example of that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM