Open In App

Convert date string to timestamp in Python

The Most Common way we use to store dates and times into a Database is in the form of a timestamp.

date and time in form of a string before storing it into a database, we convert that date and time string into a timestamp. Python provides various ways of converting the date to timestamp. Few of them discussed in this article are:



Convert date string to timestamp Using timetuple()

Approach:

Example 1: 






# Python program to convert
# date to timestamp
 
 
import time
import datetime
 
 
string = "20/01/2020"
print(time.mktime(datetime.datetime.strptime(string,
                                            "%d/%m/%Y").timetuple()))

Output:

1579458600.0

Time complexity: O(1)
Auxiliary space: O(1)

Example 2: 




# Python program to convert
# date to timestamp
 
 
 
import time
import datetime
 
 
string = "20/01/2020"
 
element = datetime.datetime.strptime(string,"%d/%m/%Y")
 
tuple = element.timetuple()
timestamp = time.mktime(tuple)
 
print(timestamp)

Output:

1579458600.0

Time complexity: O(1)
Auxiliary space: O(1)

Convert date string to timestamp Using timestamp()

Approach:

Example 1: 




# Python program to convert
# date to timestamp
 
 
import time
import datetime
 
 
string = "20/01/2020"
 
 
element = datetime.datetime.strptime(string,"%d/%m/%Y")
 
timestamp = datetime.datetime.timestamp(element)
print(timestamp)

Output:

1579458600.0

Article Tags :