python 2.4中datetime有strftime方法,而无strptime方法。不能对字符串进行格式转换。比如不能将“2013-10-22”转化为日期。
2.4中字符串转日期并相减?怎么做?
必须google,不能百度:
import time
format = '%Y-%m-%d %H:%M:%S'
print time.mktime(time.strptime(time2, format)) - time.mktime(time.strptime(time1, format))
For Python 2.5+,just use datetime
from datetime import datetimeformat = '%Y-%m-%d %H:%M:%S'print datetime.strptime(time2, format) - datetime.strptime(time1, format)# 1 day, 0:00:00
#time1 and time 2 are string as date, like "2013-10-22"
此外2.4中还可以:
from time import strptime
from datetime import datetime
str_to_datetime = lambda st: datetime(*strptime(st, '%Y-%m-%d %H:%M:%S')[:6])
str_to_datetime('2010-04-20 10:07:30')
或者
import time
time1 = "2010-04-20 10:07:30"
time_tuple = time.strptime(time1, "%Y-%m-%d %H:%M:%S")
timestamp = time.mktime(time_tuple)
而实际上还可以用
datetime(*(time.strptime(date_string, format)[0:6]))
拆开:
t = time.strptime(timepoint, '%Y-%m-%d')
resulttime = datetime.datetime(*t[:6])