如何*更改*struct_time对象?

Ale*_*lex 12 python time

在python中处理时间和日期时,你会偶然发现time.struct_time对象:

st = time.strptime("23.10.2012", "%d.%m.%Y")
print st
time.struct_time(tm_year=2012, tm_mon=10, tm_mday=23, tm_hour=0, tm_min=0,
                 tm_sec=0, tm_wday=1, tm_yday=297, tm_isdst=-1)
Run Code Online (Sandbox Code Playgroud)

现在因为这个结构不支持项目分配(即你不能做类似的事情st[1]+=1),所以还有可能增加月份的数量.

解决方案建议将此time_struct转换为秒并添加相应的秒数,但这看起来不太好.您还需要知道一个月中的天数,或者年份是否为闰年.我想要一个简单的方法来获得一个time_struct,例如

time.struct_time(tm_year=2012, tm_mon=11, tm_mday=23, tm_hour=0, tm_min=0,
                 tm_sec=0, tm_wday=1, tm_yday=297, tm_isdst=-1)
Run Code Online (Sandbox Code Playgroud)

只有一个月增加了一个.time_struct从头开始创建很好 - 但是如何?有什么方法?

Mar*_*ers 20

而是使用datetime模块,它具有更丰富的对象集来处理日期(时间)算术:

import datetime
adate = datetime.datetime.strptime("23.10.2012", "%d.%m.%Y").date()
adate + datetime.timedelta(days=30)
Run Code Online (Sandbox Code Playgroud)

您可以使用优秀的python-dateutil附加模块来获得更丰富的选项来处理增量:

from dateutil.relativedelta import relativedelta
adate + relativedelta(months=1)
Run Code Online (Sandbox Code Playgroud)

relativedelta 知道闰年,月份长度等,并且在1月30日增加一个月时会做正确的事情(你最终会在2月28日或29日结束,它不会越过月份界限).

  • @mgilson:这就是为什么我建议使用“dateutil.relativedelta”。 (2认同)

小智 9

所以...这里的文档中给出了基于time_struct的元组的模式:http: //docs.python.org/2/library/time.html#time.struct_time

即使它只是作为time_struct的只读,你可以使用强制转换为list()来直接获取该元组(记住在增加它之后回绕你的月份,并将结束范围保持在1-12而不是0 -11).然后该time.struct_time()函数将有效的9元组转换回time_struct:

st = time.strptime("23.10.2012", "%d.%m.%Y")
st_writable = list(st)
st_writable[1] = (st_writable[1] + 1)%12 + 1
st = time.struct_time(tuple(st_writable))
Run Code Online (Sandbox Code Playgroud)

  • 可以通过执行一些“元组”算术来避免转换为“列表”,即“st = time.struct_time((st[0],) + ((st[1]+1)%12 + 1,) + st[2:])`。 (3认同)