Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 321
Rajeev Avatar asked Nov 15 '10 11:11

Rajeev


People also ask

How do I convert string to time in Python?

We can convert a string to datetime using strptime() function. This function is available in datetime and time modules to parse a string to datetime and time objects respectively.

How do you convert string to UTC time in Python?

Python convert a string to datetime with timezone In this example, I have imported a module called timezone. datetime. now(timezone('UTC')) is used to get the present time with timezone. The format is assigned as time = “%Y-%m-%d %H:%M:%S%Z%z”.

How do you convert a string to a date object in Python?

Method 1: Program to convert string to DateTime using datetime. strptime() function. strptime() is available in DateTime and time modules and is used for Date-Time Conversion. This function changes the given string of datetime into the desired format.

Is there a time datatype in Python?

In Python, date and time are not a data type of their own, but a module named datetime can be imported to work with the date as well as time. Python Datetime module comes built into Python, so there is no need to install it externally. Python Datetime module supplies classes to work with date and time.


1 Answers

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
like image 198
knitti Avatar answered Oct 17 '22 06:10

knitti