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

SilentGhost
  • 307,395
  • 66
  • 306
  • 293
Rajeev
  • 44,985
  • 76
  • 186
  • 285

4 Answers4

25

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
knitti
  • 6,817
  • 31
  • 42
3
>>> 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
John La Rooy
  • 295,403
  • 53
  • 369
  • 502
3

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.

rubayeet
  • 9,269
  • 8
  • 46
  • 55
-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)
mouad
  • 67,571
  • 18
  • 114
  • 106