【问题标题】:Is there a wildcard format directive for strptime?strptime 是否有通配符格式指令?
【发布时间】:2012-04-15 03:07:56
【问题描述】:

我正在像这样使用strptime

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

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

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

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

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

【问题讨论】:

    标签: python time timezone strptime


    【解决方案1】:

    没有通配符运算符。 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")
    

    【讨论】:

      【解决方案2】:

      我们开发了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)
      

      【讨论】:

        猜你喜欢
        • 2012-05-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-12-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多