Related Articles

Related Articles

Convert date string to timestamp in Python
  • Last Updated : 29 Dec, 2020

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()

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:

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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()))

chevron_right


Output:

1579458600.0

Example 2:



filter_none

edit
close

play_arrow

link
brightness_4
code

# 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)

chevron_right


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:

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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)

chevron_right


Output:

1579458600.0

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.




My Personal Notes arrow_drop_up
Recommended Articles
Page :