How to convert datetime to time float (unix timestamp) in Python 2
Use this snippet to convert a datetime.datetime
object into a float
(like the one time.time()
returns) in Python 2.x:
datetime_to_timestamp_example.py
from datetime import datetime
import time
dt = datetime.now()
timestamp = time.mktime(dt.timetuple()) + dt.microsecond/1e6
datetime_to_timestamp_snippet.py
After running this, timestamp will be `1563812373.1795` for example.
or use this function:
```python
from datetime import datetime
import time
def datetime_to_timestamp(dt):
return time.mktime(dt.timetuple()) + dt.microsecond/1e6
datetime_to_timestamp_func.py
In Python 3, you can simply use
```python
dt.timestamp()
but that is not supported in Python 2.
Check out similar posts by category:
Python
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow