Convert date to timestamp in Python
In many Databases date and time are stored in timestamp format. Converting date and time from strings format into timestamp format we can do this using Python. We mostly encounter date and time in string format and in different date formats. To overcome this problem we can convert a string format date and time into timestamp format easily using Python.You can also get more knowledge fromĀ Formatting dates in Python
We can get Timestamp from any string format. We can use the below methods to do this.
- timetuple()
- timestamp()
Here is the code in Python.
Convert date to timestamp – First example
In this example, we will look into a date format of dd/mm/yyyy. Using timetuple method.
Code:
#Giving date and time in string format da = "15/08/2002" #getting timestamp ind = datetime.datetime.strptime(da,"%d/%m/%Y") ts = time.mktime(ind.timetuple()) print(ts)
Output:
1029349800.0
You can also use any format of date and time. One more example is given below to explain this.
Example 2:
In this example, we will look into a different date format yyyy-dd-mm. Using timetuple method.
Code:
# importing required libraries import time import datetime #Giving date and time in string format da = "2002-22-12" #getting timestamp ind = datetime.datetime.strptime(da,"%Y-%d-%m") tup = ind.timetuple() ts = time.mktime(tup) print(ts)
Output:
1040495400.0
Convert date to timestamp in Python using timestamp method
In this example, we will convert date from string to timestamp using timestamp method.
Code:
#importing all required libraries import datetime #getting date in string format da = "01/01/2022" ind = datetime.datetime.strptime(da, "%d/%m/%Y") #getting timestamp ts_da = ind.timestamp() print(ts_da)
Output:
1640975400.0
By learning the above 3 examples you can try on any date and time format and get the timestamp. Now, we can use this timestamp to add in any kind of database that supports timestamp.
Leave a Reply