strptime是否有通配符格式指令?

时间:2012-03-31 21:20:51

标签: python time timezone strptime

我正在使用strptime这样:

import time
time.strptime("+10:00","+%H:%M")

但“+10:00”也可能是“-10:00”(与UTC的时区偏移),这将破坏上述命令。我可以用

time.strptime("+10:00"[1:],"%H:%M")

但理想情况下,我发现在格式代码前使用通配符更具可读性。

Python的strptime / strftime是否存在这样的通配符运算符?

2 个答案:

答案 0 :(得分:3)

没有通配符运算符。 strptime支持的list of format directives位于文档中。

您正在寻找的是%z格式指令,它支持表单+HHMM-HHMM形式的时区表示。虽然datetime.strftime支持了一段时间,但只有strptime starting in Python 3.2才支持。

在Python 2上,处理此问题的最佳方法可能是使用datetime.datetime.strptime,手动处理负偏移,并获得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)

在Python 3.2中,删除:并使用%z

import time
tz = "+10:00"
tz_toconvert = tz[:3] + tz[4:]
tz_struct_time = time.strptime(tz_toconvert, "%z")

答案 1 :(得分:0)

我们开发了datetime-glob来解析由一致日期/时间格式生成的文件列表中的日期/时间。从模块的文档:

>>> 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)
相关问题