DateTime to Unix timestamp
For converting Python DateTime to Unix timestamp, we’ve imported a module called datetime and time in this example, and the variable date_time has been declared and assigned datetime. time/date (2021, 7, 26, 21, 20). The year is 2021, the month is 7, the day is 26, the hour is 21, and the minute is 20.
Code:
Python3
# importing datetime module import datetime import time # assigned regular string date date_time = datetime.datetime( 2021 , 7 , 26 , 21 , 20 ) # print regular python date&time print ( "date_time =>" ,date_time) # displaying unix timestamp after conversion print ( "unix_timestamp => " , (time.mktime(date_time.timetuple()))) |
Output:
date_time => 2021-07-26 21:20:00 unix_timestamp => 1627314600.0
Explanation:
Date and time manipulation classes are provided by the datetime module. The inverse function of local time is mktime(). It accepts a struct time or a full 9-tuple as an argument and returns a floating-point number to be compatible with time (). It is also used to convert a datetime to a Unix timestamp.
The timetuple() method of datetime.date objects return a time object.struct time. The struct time object is a named tuple that may be retrieved using either an index or by name. The year, month, and day fields of the named tuple returned by the timetuple() function will be set according to the date object, while the hour, minutes, and seconds fields will be set to zero.
How to Convert DateTime to UNIX Timestamp in Python ?
The Unix timestamp is a single signed integer that grows by one every second, allowing computers to store and manipulate conventional date systems. The software is then translated into a human-readable format. The Unix timestamp is the number of seconds calculated since January 1, 1970. In this article, we are going to see how to convert DateTime to Unix timestamp.