Pergunta

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

How to convert the above from string to time stamp?

I need to subtract the above timestamps time2-time1.

Foi útil?

Solução

For 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

Edit: for 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

Outras dicas

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

If you're stuck on Python 2.4 system like me:

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

Otherwise datetime.strptime() will work just fine.

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)
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top