Search code examples
pythondatetimestrptime

str to time in python


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.


Solution

  • 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