strptime 是否有通配符格式指令? [英] Is there a wildcard format directive for strptime?

查看:33
本文介绍了strptime 是否有通配符格式指令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我像这样使用 strptime:

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

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

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.

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

Does such a wildcard operator exist for Python's strptime / strftime?

推荐答案

没有通配符运算符.strptime 支持的格式指令列表在文档中.

There is no wildcard operator. The list of format directives supported by strptime is in the docs.

您正在寻找的是 %z 格式指令,它支持 +HHMM-HHMM 形式的时区表示代码>.虽然 datetime.strftime 已经支持它一段时间了,但它只支持 strptime 从 Python 3.2 开始.

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.

在 Python 2 上,处理此问题的最佳方法可能是使用 datetime.datetime.strptime,手动处理负偏移,得到一个datetime.timedelta:

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)

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

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

这篇关于strptime 是否有通配符格式指令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆