Convert date string to timestamp in Python


When it is required to convert a string into a timestamp, the ‘mktime’ method is used. This method is present in the ‘time’ package.

Below is a demonstration of the same −

Example

 Live Demo

import time
import datetime

my_string = "24/03/2021"
print("The date string is :")
print(my_string)
print("The timestamp is :")
print(time.mktime(datetime.datetime.strptime(my_string, "%d/%m/%Y").timetuple()))

Output

The date string is :
24/03/2021
The timestamp is :
1616544000.0

Explanation

  • The required packages are imported.

  • The string is defined, and displayed on the console.

  • The ‘mktime’ method from time package is called, and the string is passed as parameter to it.

  • The ‘strptime’ is used to remove the extra spaces or symbols from the string.

  • The output is displayed on the console.

Updated on: 15-Apr-2021

996 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements