5 Best Ways to Convert String to Datetime and Vice Versa in Python

πŸ’‘ Problem Formulation: In Python, handling date and time is a common requirement. Often, you’ll need to convert a string representation of a date and time to a datetime object for manipulation, then possibly back to a string for formatting or storage. For example, converting the string “2022-03-01 14:38:00” to a datetime object, manipulate, then revert back to a string “03-01-2022 02:38 PM”.

Method 1: Using strptime and strftime from datetime Module

This method uses the built-in datetime module, leveraging strptime to convert a string to a datetime object based on a format specifier, and strftime to format a datetime object back into a string.

Here’s an example:

from datetime import datetime
dt_string = "2022-03-01 14:38:00"
dt_object = datetime.strptime(dt_string, '%Y-%m-%d %H:%M:%S')
formatted_string = dt_object.strftime('%m-%d-%Y %I:%M %p')

print(dt_object)
print(formatted_string)

The output of this code will be:

2022-03-01 14:38:00
03-01-2022 02:38 PM

This code first creates a datetime object by parsing a string with a specified format. Then it converts that datetime object back into a string with a new format.

Method 2: Using dateutil.parser

The dateutil module’s parser is adept at recognizing and parsing most common date formats automatically. This method shines when the date format might not be known in advance.

Here’s an example:

from dateutil import parser
dt_string = "March 1st, 2022 2:38 PM"
dt_object = parser.parse(dt_string)
formatted_string = dt_object.strftime('%Y-%m-%d %H:%M:%S')

print(dt_object)
print(formatted_string)

The output of this code will be:

2022-03-01 14:38:00
2022-03-01 14:38:00

By using the dateutil.parser, the code automatically parses a human-readable date format into a datetime object, then formats it back using strftime.

Method 3: Using pandas.to_datetime() and DataFrame.strftime()

The pandas library offers vectorized datetime conversions for series and dataframes, which can be handy for dealing with datasets. It can convert different string formats to datetime seamlessly and vice versa.

Here’s an example:

import pandas as pd
dt_series = pd.Series(["2022/03/01 14:38:00", "2022/03/02 16:50:00"])
dt_objects = pd.to_datetime(dt_series, format='%Y/%m/%d %H:%M:%S')
formatted_strings = dt_objects.dt.strftime('%m-%d-%Y %I:%M %p')

print(dt_objects)
print(formatted_strings)

The output of this code will be:

DatetimeIndex(['2022-03-01 14:38:00', '2022-03-02 16:50:00'], dtype='datetime64[ns]', freq=None)
0    03-01-2022 02:38 PM
1    03-02-2022 04:50 PM
dtype: object

By using pandas, the code converts a series of date strings to a DatetimeIndex object, and then back to the desired string format, capable of handling multiple dates at once.

Method 4: Using arrow.get() and arrow.format()

Arrow is a modern datetime library for Python that provides methods for creation, manipulation, formatting, and conversion of date, time, and timestamps. It can handle parsing and formatting operations with ease.

Here’s an example:

import arrow
dt_string = "2022-03-01T14:38:00+00:00"
dt_object = arrow.get(dt_string)
formatted_string = dt_object.format('MM-DD-YYYY hh:mm A')

print(dt_object)
print(formatted_string)

The output of this code will be:

2022-03-01T14:38:00+00:00
03-01-2022 02:38 PM

Using the arrow library, the code snippet above parses a ISO 8601 formatted string into an Arrow object, which is then formatted back into a human-readable string.

Bonus One-Liner Method 5: Using pendulum.parse() and pendulum.to_formatted_date_string()

Pendulum is another datetime library that is renowned for being easy to use. It provides quick functionalities to parse strings to datetime and format them with ease.

Here’s an example:

import pendulum
dt_string = "2022-03-01 14:38:00"
dt_object = pendulum.parse(dt_string)
formatted_string = dt_object.to_formatted_date_string()

print(dt_object)
print(formatted_string)

The output of this code will be:

2022-03-01T14:38:00+00:00
Mar 1st, 2022

This code snippet demonstrates the parsing of a standard datetime string into a Pendulum datetime object and then obtains a human-readable date string.

Summary/Discussion

  • Method 1: Using strptime and strftime. Strengths: built-in and reliable, no extra dependencies required. Weaknesses: requires format specifiers to be known and correctly input by the developer.
  • Method 2: Using dateutil.parser. Strengths: highly flexible, great for parsing human-readable dates. Weaknesses: external dependency that may not be as fast as built-in solutions.
  • Method 3: Using pandas functions. Strengths: handles datasets and vectorized operations well. Weaknesses: more suited for data analysis tasks, overkill for simple conversions.
  • Method 4: Using arrow. Strengths: easy to use, modern solution with a range of manipulation methods. Weaknesses: another external dependency.
  • Bonus Method 5: Using pendulum. Strengths: user-friendly and concise. Weaknesses: while powerful, it’s yet another library to maintain within your project.