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
.
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.
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”.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With