Is there a wildcard format directive for strptime?

放肆的年华 提交于 2019-12-07 05:17:39

问题


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?


回答1:


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")



回答2:


We developed datetime-glob to parse date/times from a list of files generated by a consistent date/time formatting. From the module's documentation:

>>> import datetime_glob
>>> matcher = datetime_glob.Matcher(
                         pattern='/some/path/*%Y-%m-%dT%H-%M-%SZ.jpg')

>>> matcher.match(path='/some/path/some-text2016-07-03T21-22-23Z.jpg')
datetime_glob.Match(year = 2016, month = 7, day = 3, 
                    hour = 21, minute = 22, second = 23, microsecond = None)

>>> match.as_datetime()
datetime.datetime(2016, 7, 3, 21, 22, 23)


来源:https://stackoverflow.com/questions/9959778/is-there-a-wildcard-format-directive-for-strptime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!