Program to convert date string to timestamp using Python

Introduction

While storing the date and time into database, we first convert it to timestamp and then store it. Our task is to convert the date to timestamp and print it.

Program

Approach 1:

Program to convert date string to timestamp using Python

Output:

Program to convert date string to timestamp using Python Output

Approach 2:

import datetime
import time
date_str = '30/11/2020'
temp = datetime.datetime.strptime(date_str, "%d/%m/%Y")
op_timestamp = datetime.datetime.timestamp(temp)
print("The converted date to timestamp is: ", op_timestamp)

Output:

Program to convert date string to timestamp using Python Output 2

Explanation

In approach 1, we have used timetuple() function. By using strptime() method, the input string is converted to date object and by using timetuple() we have converted the date object to tuple. At last we used mktime() to convert the tuple to timestamp.

In approach 2 we have used timestamp() function. We have stored the input date value in a variable and converted it to date object. We have used timestamp() on converted date object to convert it into timestamp value and returned the value.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.