How to convert NumPy datetime64 to Timestamp?
Last Updated :
03 Oct, 2022
In this article, we will discuss how to convert NumPy datetime64 to Timestamp in Python.
Example:
Input:
If the current datetime64 is as follows: 2020-08-18 09:31:51.944622
Output:
The required timestamp in seconds will be: 1597743111.944622
The required timestamp in minutes will be: 26629051.8657437
The required timestamp in an hour will be: 443817.53109572834
Example 1:
Here we are taking the date through np.datetime64() and then subtracting that date from the default system date which is 1970-01-01T00:00:00Z. and with the help of np.timedelta64() converting the date into seconds, minutes, and hours.
Python3
import numpy as np
from datetime import datetime
date = datetime.utcnow()
print ( "Printing the Current date:" ,
date)
date64 = np.datetime64(date)
ts = (date64 - np.datetime64( '1970-01-01T00:00:00Z' ))
/ np.timedelta64( 1 , 's' )
print ("Printing the converted datetime
in Timestamp in seconds:", ts)
tm = (date64 - np.datetime64( '1970-01-01T00:00:00Z' ))
/ np.timedelta64( 1 , 'm' )
print ("Printing the converted datetime
in Timestamp in minutes:", ts)
th = (date64 - np.datetime64( '1970-01-01T00:00:00Z' ))
/ np.timedelta64( 1 , 'h' )
print ("Printing the converted datetime
in Timestamp in hour:", th)
|
Output:
Printing the Current date: 2020-08-26 10:07:54.820878
Printing the converted datetime in Timestamp in seconds: 1598436474.820878
Printing the converted datetime in Timestamp in minutes: 1598436474.820878
Printing the converted datetime in Timestamp in hour: 444010.13189468835
Example2:
Converting 15 Aug 2020 in seconds, minutes and hour timestamp and following the same approach as mentioned above i.e. convert numpy.datetime64 to timestamp.
Python3
import numpy as np
from datetime import datetime
print ( "Printing the date:" )
dt64 = np.datetime64( '2020-08-15' );
print (dt64)
ts = (dt64 - np.datetime64( '1970-01-01T00:00:00Z' )) / np.timedelta64( 1 , 's' )
print ( "Printing the converted datetime in Timestamp in seconds:" ,
ts)
print ( "Printing the converted datetime in Timestamp in minutes" )
tm = (dt64 - np.datetime64( '1970-01-01T00:00:00Z' )) / np.timedelta64( 1 , 'm' )
print (tm)
print ( "Printing the converted datetime in Timestamp in hour" )
th = (dt64 - np.datetime64( '1970-01-01T00:00:00Z' )) / np.timedelta64( 1 , 'h' )
print (th)
|
Output:
Printing the date: 2020-08-15 Printing the converted datetime in Timestamp in seconds: 1597449600.0 Printing the converted datetime in Timestamp in minutes 26624160.0 Printing the converted datetime in Timestamp in hour 443736.0
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...