w3resource

Python: Convert a string date to the timestamp


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.



Follow us on Facebook and Twitter for latest update.