简体   繁体   中英

Python parse string as date without certain elements

I'm using time.strptime to parse a string as a date, but the string does not have a year associated with it. How can I add the current year to the date object?

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

http://ideone.com/vI9S0

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

This is far from the only way to do it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM