In this article, you will learn how to convert a string date to a timestamp in python. A timestamp is a common way to store date and time in a database. When you receive a date and time in form of a string before storing it into a database, then you convert that date and time string into a timestamp. In Python, there are various ways to convert a string date to a timestamp. In this article, we are using .timestamp()
and using .timetuple()
to convert a string date to a timestamp in python.
In this example, we used the datetime.datetime.strptime()
to convert the string DateTime to the datetime
object and datetime.datetime.timestamp()
to convert the datetime
object to the timestamp. This approach is used to convert DateTime to the timestamp in the local timezone. The .timestamp()
assumes local time instead of UTC if no explicit timezone is given. And this function assumes the DateTime is midnight “05/03/2021”.
# Import Module
import time
import datetime
date_string = "05/03/2021"
date = datetime.datetime.strptime(date_string, "%d/%m/%Y")
timestamp = datetime.datetime.timestamp(date)
# Print Output
print("Date Converted to TimeStamp: ",timestamp)
Date Converted to TimeStamp: 1614882600.0
In this example, we used the datetime.datetime.strptime()
to convert the string DateTime to the datetime
object and the timetuple()
method returns a named tuple of type time.struct_time. These attributes are,
And the mktime()
is the inverse function of localtime()
. Its argument is the struct_time
or full 9-tuple and it returns a floating-point number, for compatibility with time()
.
# Import Module
import time
import datetime
date_string = "05/03/2021"
date = datetime.datetime.strptime(date_string, "%d/%m/%Y")
time_tuple = date.timetuple()
timestamp = time.mktime(time_tuple)
# print output
print("Date Converted to TimeStamp: ",timestamp)
Date Converted to TimeStamp: 1614882600.0
# Import Module
import time
import datetime
string = "05/03/2021"
timestamp = time.mktime(datetime.datetime.strptime(string,
"%d/%m/%Y").timetuple())
# Print Output
print("Date Converted to TimeStamp: ",timestamp)
Date Converted to TimeStamp: 1614882600.0
I hope this article will help you to understand how to convert a string date to a timestamp in python.
Share your valuable feedback, please post your comment at the bottom of this article. Thank you!
Comments