Convert date string to timestamp in Python



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. When we receive a 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:

  • Using timetuple()
  • Using timestamp()

Using timetuple()

Approach:

  • import datetime is use to import the date and time modules
  • After importing date time module next step is to accept date string as an input and then store it into a variable
  • Then we use strptime method. This method takes two arguments:
    • First argument is the string format of the date and time
    • Second argument is the format of the input string
  • We convert date and time string into a date object
  • Then we use timetuple() to convert date object into tuple
  • At the end we use mktime(tuple) to convert the Date tuple into a timestamp.

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

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

Using timestamp()

Approach:

  • import datetime is use to import the date and time modules
  • After importing date time module next step is to accept date string as an input and then store it into a variable
  • Then we use strptime method. This method takes two arguments
    • First arguments s the string format of the date and time
    • Second argument is the format of the input string
  • Then it returns date and time value in timestamp format and we stored this in timestamp variable.

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

 

Last Updated on October 28, 2021 by admin

Leave a Reply

Your email address will not be published. Required fields are marked *

Recommended Blogs