Convert an array of datetimes into an array of strings with pytz timezone object in Python

PythonServer Side ProgrammingProgramming

To convert an array of datetimes into an array of strings, use the numpy.datetime_as_string() method in Python Numpy. The method returns an array of strings the same shape as the input array. The first parameter is the array of UTC timestamps to format.

The second parameter is the "timezone", the Timezone information to use when displaying the datetime. If ‘UTC’, end with a Z to indicate UTC time. If ‘local’, convert to the local timezone first, and suffix with a +-#### timezone offset. If a tzinfo object, then do as with ‘local’, but use the specified timezone.

Steps

At first, import the required libraries. For pytz timezone, we have imported the 'pytz' library −

import numpy as np
import pytz

Create an array of datetime. The 'M' type specifies datetime −

arr = np.arange('2022-02-20T03:25', 6*60, 60, dtype='M8[m]')

Displaying our array −

print("Array...\n",arr)

Get the datatype −

print("\nArray datatype...\n",arr.dtype)

Get the dimensions of the Array −

print("\nArray Dimensions...\n",arr.ndim)

Get the shape of the Array −

print("\nOur Array Shape...\n",arr.shape)

Get the number of elements of the Array −

print("\nNumber of elements in the Array...\n",arr.size)

To convert an array of datetimes into an array of strings, use the numpy.datetime_as_string() method. The method returns an array of strings the same shape as the input array −

print("\nResult...\n",np.datetime_as_string(arr, timezone=pytz.timezone('US/Eastern')))

Example

import numpy as np
import pytz

# Create an array of datetime
# The 'M' type specifies datetime
arr = np.arange('2022-02-20T03:25', 6*60, 60, dtype='M8[m]')

# Displaying our array
print("Array...\n",arr)

# Get the datatype
print("\nArray datatype...\n",arr.dtype)

# Get the dimensions of the Array
print("\nArray Dimensions...\n",arr.ndim)

# Get the shape of the Array
print("\nOur Array Shape...\n",arr.shape)

# Get the number of elements of the Array
print("\nNumber of elements in the Array...\n",arr.size)

# To convert an array of datetimes into an array of strings, use the numpy.datetime_as_string() method in Python Numpy
# The method returns an array of strings the same shape as the input array
print("\nResult...\n",np.datetime_as_string(arr, timezone=pytz.timezone('US/Eastern')))

Output

Array...
['2022-02-20T03:25' '2022-02-20T04:25' '2022-02-20T05:25'
'2022-02-20T06:25' '2022-02-20T07:25' '2022-02-20T08:25']

Array datatype...
datetime64[m]

Array Dimensions...
1

Our Array Shape...
(6,)

Number of elements in the Array...
6

Result...
['2022-02-19T22:25-0500' '2022-02-19T23:25-0500' '2022-02-20T00:25-0500'
'2022-02-20T01:25-0500' '2022-02-20T02:25-0500' '2022-02-20T03:25-0500']
raja
Updated on 24-Feb-2022 10:20:48

Advertisements