time1 = "2010-04-20 10:07:30"
time2 = "2010-04-21 10:07:30"
如何将上述字符串转换为时间戳?
我需要减去上面的时间戳time2-time1
。
答案 0 :(得分:22)
对于Python 2.5 +
from datetime import datetime
format = '%Y-%m-%d %H:%M:%S'
print datetime.strptime(time2, format) -
datetime.strptime(time1, format)
# 1 day, 0:00:00
适用于Python 2.4的编辑
import time
format = '%Y-%m-%d %H:%M:%S'
print time.mktime(time.strptime(time2, format)) -
time.mktime(time.strptime(time1, format))
# 86400.0
答案 1 :(得分:3)
如果你像我一样坚持使用Python 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')
否则datetime.strptime()会正常工作。
答案 2 :(得分:2)
>>> t1 = datetime.strptime(time1, "%Y-%m-%d %H:%M:%S")
>>> t2 = datetime.strptime(time2, "%Y-%m-%d %H:%M:%S")
>>> t2-t1
datetime.timedelta(1)
>>> (t2-t1).days
1
>>> (t2-t1).seconds
0
答案 3 :(得分:-1)
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)