Sometimes, we want to convert between datetime, timestamp and datetime64 with Python.
In this article, we’ll look at how to convert between datetime, timestamp and datetime64 with Python.
How to convert between datetime, timestamp and datetime64 with Python?
To convert between datetime, timestamp and datetime64 with Python, we can use the Pandas’ Timestamp
class to create a Pandas timestamp.
And we can use the numpy’s datetime64
method to create a numpy date time object.
For instance, we write:
import numpy as np
import pandas as pd
ts = pd.Timestamp(np.datetime64('2020-05-01T01:00:00.000000'))
print(ts)
dt = np.datetime64('2012-05-01T01:00:00.000000+0100')
print(dt)
We call pd.Timestamp
with a nummpy datetime64
object to convert it to a Pandas timestamp.
Then we call the np.datetime64
method with a date time string to convert it to a numpy’s date time 64 object.
Therefore, ts
is 2020-05-01 01:00:00
.
And dt
is 2012-05-01T00:00:00.000000
.
Conclusion
To convert between datetime, timestamp and datetime64 with Python, we can use the Pandas’ Timestamp
class to create a Pandas timestamp.
And we can use the numpy’s datetime64
method to create a numpy date time object.