w3resource

Python: Convert a date to timestamp

Python Datetime: Exercise-30 with Solution

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

Sample Solution:

Python Code:

# Import the time module
import time
# Import the datetime module
import datetime

# Get the current date and time
now = datetime.datetime.now()

# Print the UNIX timestamp representing the current date and time
# The mktime function is used to convert the time tuple returned by now().timetuple() to a UNIX timestamp
print()
print(time.mktime(now.timetuple()))
print() 

Output:

1494224813.0

Explanation:

In the exercise above,

  • The code imports the "time" and "datetime" modules.
  • Get the current date and time:
    • It retrieves the current date and time using the "datetime.now()" method, which returns a 'datetime' object representing the current date and time.
  • Converting to UNIX Timestamp:
    • It converts the current date and time (now) to a UNIX timestamp using the "mktime()" function from the 'time' module.
    • The "timetuple()" method of the 'datetime' object converts the 'datetime' object to a time tuple, which "mktime()" generates the UNIX timestamp.
  • Finally it prints the UNIX timestamp representing the current date and time to the console.

Flowchart:

Flowchart: Convert a date to timestamp.

Python Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Python program to get the GMT and local current time.
Next: Write a Python program convert a string date to the timestamp.

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.