I'm using strptime
like this:
import time
time.strptime("+10:00","+%H:%M")
but "+10:00" could also be "-10:00" (timezone offset from UTC) which would break the above command. I could use
time.strptime("+10:00"[1:],"%H:%M")
but ideally I'd find it more readable to use a wildcard in front of the format code.
Does such a wildcard operator exist for Python's strptime
/ strftime
?
strptime is short for "parse time" where strftime is for "formatting time". That is, strptime is the opposite of strftime though they use, conveniently, the same formatting specification.
Python time strptime() MethodThe format parameter uses the same directives as those used by strftime(); it defaults to "%a %b %d %H:%M:%S %Y" which matches the formatting returned by ctime(). If string cannot be parsed according to format, or if it has excess data after parsing, ValueError is raised.
p for produce, str p time (strptime)-> string produces time.
The strftime() method returns a string representing date and time using date, time or datetime object.
There is no wildcard operator. The list of format directives supported by strptime
is in the docs.
What you're looking for is the %z
format directive, which supports a representation of the timezone of the form +HHMM
or -HHMM
. While it has been supported by datetime.strftime
for some time, it is only supported in strptime
starting in Python 3.2.
On Python 2, the best way to handle this is probably to use datetime.datetime.strptime
, manually handle the negative offset, and get a datetime.timedelta
:
import datetime
tz = "+10:00"
def tz_to_timedelta(tz):
min = datetime.datetime.strptime('', '')
try:
return -(datetime.datetime.strptime(tz,"-%H:%M") - min)
except ValueError:
return datetime.datetime.strptime(tz,"+%H:%M") - min
print tz_to_timedelta(tz)
In Python 3.2, remove the :
and use %z
:
import time
tz = "+10:00"
tz_toconvert = tz[:3] + tz[4:]
tz_struct_time = time.strptime(tz_toconvert, "%z")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With