w3resource

Python: Convert a string date to the timestamp

Python Datetime: Exercise-31 with Solution

Write a Python program to convert a string date to a timestamp.

Sample Solution:

Python Code:

# Import the time module
import time
# Import the datetime module
import datetime
# Assign a date string to the variable 's'
s = "01/10/2016"
# Print an empty line
print()
# Convert the date string to a timestamp using datetime module and print it
print(time.mktime(datetime.datetime.strptime(s, "%d/%m/%Y").timetuple()))
# Print an empty line
print()

Output:

1494225605.0  

Explanation:

In the exercise above,

  • The code imports two modules: "time" and "datetime".
  • It assigns a date string "01/10/2016" to the variable 's'. This string represents the date in the format of "day/month/year".
  • Next, it converts the date string 's' into a timestamp using the "strptime()" method from the "datetime" module to parse the string into a datetime object, and then "mktime()" function from the "time" module to convert the datetime object into a Unix timestamp (the number of seconds since the Unix epoch - January 1, 1970).
  • Finally, it prints the calculated timestamp.

Flowchart:

Flowchart: Convert a string date to the timestamp.

Python Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Python program convert a date to timestamp.
Next: Write a Python program to calculate a number of days between two dates.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/python-exercises/date-time-exercise/python-date-time-exercise-31.php