Converting Datetime Objects to Epoch Time (Unix Time) in Python
In Python, converting datetime objects to Unix time, or milliseconds since the 1970 epoch, is a common task. The following question delves into how to accomplish this conversion effectively:
Question:
How can I convert a Python datetime object to unix time, or seconds/milliseconds since the 1970 epoch?
Answer:
One of the most straightforward solutions is to utilize the "unix_time_millis" function, as demonstrated below:
import datetime epoch = datetime.datetime.utcfromtimestamp(0) def unix_time_millis(dt): return (dt - epoch).total_seconds() * 1000.0
Explanation:
By using this function, you can effortlessly convert any datetime object to Unix time in milliseconds.
The above is the detailed content of How can I convert a Python datetime object to Unix time (seconds/milliseconds since the 1970 epoch)?. For more information, please follow other related articles on the PHP Chinese website!