Convert ndarrays of datetime into ndarray of strings

The numpy function datetime_as_string() converts an ndarray containing datetime64 objects as its elements into an ndarray consisting of datetime strings.

Time and Date Updated 25 Jul 2025 1 min read

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

python
# 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

Output
Type of ndarray:

            <class 'numpy.dtypes.DateTime64DType'>

            Type of ndarray:

            <class 'numpy.dtypes.StrDType'>

##