I am trying to convert a time that I receive with GMT time but I render details by time format using strptime.
from datetime import tzinfo, timedelta, datetime
ZERO = timedelta(0)
class FixedOffset(tzinfo):
"""Fixed UTC offset: `local = utc + offset`."""
def __init__(self, offset, name):
self.__offset = timedelta(hours=offset)
self.__name = name
def utcoffset(self, dt):
return self.__offset
def tzname(self, dt):
return self.__name
def dst(self, dt):
return ZERO
utc = FixedOffset(0, "UTC")
The following code shows the data that I want to convert.
Time = ("14:50:21.000 GMT Fri Apr 29 2022")
dt = datetime.strptime(Time , "%H:%M:%% GMT %% %% %% %%")
aware = dt.replace(tzinfo=FixedOffset(5, "GMT 0"))
print(aware)
print(aware.astimezone(utc))
Return the message
ValueError: time data '14:50:21.000 GMT Fri Apr 29 2022' does not match format '%H:%M:%% GMT %% %% %% %%'
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
%% is used for the % character witch is not in your source time format try this format
dt = datetime.strptime(Time , "%H:%M:%S GMT %a %b %d %Y")
or
dt = datetime.strptime(Time , "%H:%M:%S %Z %a %b %d %Y")
you can read more here on how the format argument is formulated
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0