Free cookie consent management tool by TermsFeed Convert ndarrays of datetime into ndarray of strings | Pythontic.com

Convert ndarrays of datetime into ndarray of strings

Overview:

  • SciPy represents time and date using the class datetime64. The datetime64 class does not recognise time zones. All the time objects created by datetime64 are in UTC.

  • The function numpy.datetime_as_string() converts an ndarray of datetime64 objects into an ndarray of strings.

Example:

# Example Python program that converts an ndarray of 
# datetime64 objects into strings
import numpy

# Create an ndarray of timestamps
t1 = numpy.datetime64("2025-07-25 10:12:05.132")
t2 = numpy.datetime64("2025-07-26 10:05:14.496")
t3 = numpy.datetime64("2025-07-27 10:06:12.461")
timestamps = numpy.array([t1, t2, t3])
print("Type of ndarray:")
print(type(timestamps.dtype))

# Convert the datetime64 objects to strings
timestamps_str = numpy.datetime_as_string(timestamps)

print("Type of ndarray:")
print(type(timestamps_str.dtype))

Output:

Type of ndarray:
<class 'numpy.dtypes.DateTime64DType'>
Type of ndarray:
<class 'numpy.dtypes.StrDType'>

 


Copyright 2025 © pythontic.com