python datetime strptime

Str al tiempo en Python



datetime strptime (4)

Para 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

Edición: para 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

time1 = "2010-04-20 10:07:30" time2 = "2010-04-21 10:07:30"

¿Cómo convertir lo anterior de cadena a marca de tiempo?

Necesito restar las marcas de tiempo anteriores time2-time1 .


Si estás atrapado en el sistema Python 2.4 como yo:

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

De lo contrario, datetime.strptime () funcionará bien.


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)


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