我正在使用time.strptime
将字符串解析为日期,但该字符串没有与之关联的年份。如何将当前年份添加到日期对象?
答案 0 :(得分:2)
import time, datetime
def currentyear(atime):
atime = tuple([datetime.datetime.now().year] + list(atime)[1:])
return time.localtime(time.mktime(atime))
newtime = time.strptime("19 Jan", "%d %b")
newtime = currentyear(newtime)
print newtime
答案 1 :(得分:1)
>>> import datetime
>>> import time
>>> dt = time.strptime('12/31/' + str(datetime.datetime.now().year), '%d/%M/%Y')
>>> print dt
time.struct_time(tm_year=2012, tm_mon=1, tm_mday=12, tm_hour=0, tm_min=31, tm_sec=0, tm_wday=3, tm_yday=12, tm_isdst=-1)
这远非唯一的方法。