Convert Python datetime to epoch
In this article, we are going to discuss various ways by which we can convert Python DateTime to epoch. The epoch time is also known as POSIX time which will indicate the number of seconds passed from January 1, 1970, 00:00:00 (UTC) in most Windows and Unix systems.
Note: Epoch is platform-dependent which means it depends on the system or operating system you are using.
DateTime is the time which is in the given format
year/month/day/hours/minutes/seconds: milliseconds
Using a calendar module to convert Python DateTime to epoch
Here we are using the calendar module to convert Datetime to epoch using the timetuple() function.
Python3
Output:
31536000 1625619721
Converting epoch time into DateTime using fromtimestamp
The code turns an epoch time (the number of seconds since January 1, 1970) into a DateTime format that can be read. It converts the epoch time to a DateTime object using the datetime.fromtimestamp() function. Following that, the original epoch time and the converted DateTime are printed.
Python3
Output:
Given epoch time: 33456871 Converted Datetime: 1971-01-23 11:04:31
Convert Python DateTime to epoch using strftime()
strftime() is used to convert the string DateTime to DateTime. It is also used to convert DateTime to epoch. We can get epoch from DateTime from strftime().
Syntax: datetime.datetime(timestamp).strftime(‘%s’)
Parameter:
- timestamp is the input datetime
- $s is used to get the epoch string
- datetime is the module
The parameter %s is a platform dependent format code, it works on Linux. In windows, the same code can be modified to run by %S in place of %s.
Example: Python code to convert datetime to epoch using strftime
Python3
Output:
1625599921 1614724384 1625640154 1625642760
Converting epoch time into DateTime using pytz Python Module
The code localizes a DateTime object to the Central Standard Time time zone. The code returns a DateTime object that is aware of the CST time zone. The DateTime object is 5 hours behind Universal Time (UTC).
Python3
Output:
DateTime Time zone: 2022-05-16 09:15:32-05:00
Convert Python DateTime to epoch using timestamp()
We can get epoch from DateTime using timestamp() .
Syntax: datetime.datetime(timestamp).timestamp()
Parameter:
- datetime is the module
- timestamp is the input datetime
Example: Python code to convert DateTime to epoch using timestamp()
Python3
Output:
1625596200.0 1614724384.0 1625640154.0 1625642760.0
Please Login to comment...