5 Best Ways to Convert an Array of DateTimes into an Array of Strings with Minute Precision in Python

πŸ’‘ Problem Formulation: Python developers often need to convert an array of DateTime objects into a comparable array of string representations, specifically formatted to include up to minute precision. For example, converting [datetime(2021, 3, 25, 12, 45), datetime(2021, 3, 26, 14, 30)] into ["2021-03-25 12:45", "2021-03-26 14:30"].

Method 1: Using strftime in a List Comprehension

Convert an array of DateTime objects to strings with minute precision by applying the strftime method with the desired format code. The list comprehension succinctly applies the formatting to all elements in the array.

Here’s an example:

from datetime import datetime

date_times = [datetime(2021, 3, 25, 12, 45), datetime(2021, 3, 26, 14, 30)]
strings = [dt.strftime('%Y-%m-%d %H:%M') for dt in date_times]

Output:
['2021-03-25 12:45', '2021-03-26 14:30']

The list comprehension iterates through the date_times array and uses strftime('%Y-%m-%d %H:%M') to format each datetime object into a string that includes the year, month, day, hour, and minute.

Method 2: Using datetime.fromisoformat with strftime

This method involves parsing ISO formatted date strings into datetime objects using datetime.fromisoformat before formatting them into strings with minute precision using strftime.

Here’s an example:

iso_formatted_dates = ['2021-03-25T12:45:00', '2021-03-26T14:30:00']
date_times = [datetime.fromisoformat(date) for date in iso_formatted_dates]
strings = [dt.strftime('%Y-%m-%d %H:%M') for dt in date_times]

Output:
['2021-03-25 12:45', '2021-03-26 14:30']

This method is useful when starting with ISO formatted string dates. It first converts strings to datetime objects, then formats them back into strings with the desired precision.

Method 3: Using pandas.to_datetime and Series.dt.strftime

With pandas library, you can convert a series of ISO formatted date strings into datetime objects with pandas.to_datetime and then apply strftime using the pandas Series dt accessor.

Here’s an example:

import pandas as pd

iso_formatted_dates = ['2021-03-25T12:45:00', '2021-03-26T14:30:00']
date_times = pd.to_datetime(iso_formatted_dates)
strings = date_times.dt.strftime('%Y-%m-%d %H:%M').tolist()

Output:
['2021-03-25 12:45', '2021-03-26 14:30']

Pandas makes handling arrays of dates extremely efficient, particularly for large datasets. This method takes advantage of pandas’ built-in datetime handling and formatting functionality.

Method 4: Using map Function with strftime

The map function can be used to apply strftime to each element in an array of datetime objects. This is a functional approach that some might find clearer than a list comprehension.

Here’s an example:

date_times = [datetime(2021, 3, 25, 12, 45), datetime(2021, 3, 26, 14, 30)]
strings = list(map(lambda dt: dt.strftime('%Y-%m-%d %H:%M'), date_times))

Output:
['2021-03-25 12:45', '2021-03-26 14:30']

Using map with a lambda function applies strftime to every datetime object in the array, and list converts the result back into an array of strings.

Bonus One-Liner Method 5: Using dateutil.parser.parse with List Comprehension

For flexibility in handling different date string formats, dateutil.parser.parse can parse nearly any date string into a datetime object, which can then be formatted with strftime in a list comprehension.

Here’s an example:

from dateutil.parser import parse

date_strings = ['25-03-2021 12:45', '26/03/2021 14:30']
date_times = [parse(ds) for ds in date_strings]
strings = [dt.strftime('%Y-%m-%d %H:%M') for dt in date_times]

Output:
['2021-03-25 12:45', '2021-03-26 14:30']

This method is particularly useful when dealing with date strings in inconsistent formats as dateutil.parser.parse can interpret a wide variety of date representations.

Summary/Discussion

  • Method 1: List Comprehension with strftime. Strengths: concise, readable. Weaknesses: requires datetime objects as input.
  • Method 2: ISO Format Parsing & Formatting. Strengths: handles ISO formatted strings without pandas. Weaknesses: less efficient for large datasets.
  • Method 3: pandas to_datetime & dt.strftime. Strengths: highly efficient for large datasets. Weaknesses: requires pandas installation.
  • Method 4: Functional map with strftime. Strengths: clear functional programming approach. Weaknesses: verbosity compared to list comprehension.
  • Method 5: List Comprehension with dateutil.parser.parse. Strengths: flexible format parsing. Weaknesses: requires external library, possible overhead in parsing.