5 Best Ways to Display Various Datetime Formats in Python

Rate this post

πŸ’‘ Problem Formulation: When handling datetime information in Python, it is often necessary to format dates and times in various human-readable representations. Different applications may require different datetime formats. For instance, one might need the current date and time displayed as ‘2023-03-14 16:05:09’, while another might require a more friendly version like ‘March 14th, 2023, 4:05 PM’. This article demonstrates how to achieve these formats using Python programming.

Method 1: Using the datetime module

This method involves using Python’s built-in datetime module, which provides classes for manipulating dates and times in both simple and complex ways. Here we’ll focus on the function strftime(), which allows you to format datetime objects into readable strings.

Here’s an example:

from datetime import datetime

current_time = datetime.now()
formatted_time = current_time.strftime('%Y-%m-%d %H:%M:%S')
print(formatted_time)

Output:

2023-03-14 16:05:09

This code snippet imports the datetime module and retrieves the current local date and time using datetime.now(). It then formats this datetime object to a string in the ‘YYYY-MM-DD HH:MM:SS’ format using strftime() and prints it.

Method 2: Using the time module

Python’s time module is another way to handle date and time data. The time module’s strftime() function also takes a format string and returns a string representing the time under the control of an explicit format string.

Here’s an example:

import time

current_time = time.localtime()
formatted_time = time.strftime('%B %dth, %Y, %I:%M %p', current_time)
print(formatted_time)

Output:

March 14th, 2023, 04:05 PM

This code uses the time module to obtain the current local time and formats it into a more readable string using strftime(), which is applied to a time tuple obtained from time.localtime().

Method 3: Using pandas for datetime formatting

pandas is a powerful data manipulation library that provides functionality for datetime formatting through its to_datetime and Series.dt.strftime methods. It’s particularly useful when working with time series data.

Here’s an example:

import pandas as pd

date_series = pd.Series(pd.to_datetime(['20230314', '20230315'], format='%Y%m%d'))
formatted_dates = date_series.dt.strftime('%d-%m-%Y')
print(formatted_dates)

Output:

0    14-03-2023
1    15-03-2023
dtype: object

This snippet converts a list of date strings to a pandas Series of datetime objects using pd.to_datetime(). It then formats each date in the Series to the ‘DD-MM-YYYY’ format using Series.dt.strftime() and prints the results.

Method 4: Using arrow for international datetime formatting

The arrow library provides a friendly approach to creating, manipulating, formatting and converting dates, times, and timestamps. International support is a key feature, and it follows the ‘strftime’ reference for formatting.

Here’s an example:

import arrow

current_time = arrow.now()
formatted_time = current_time.format('YYYY-MM-DD HH:mm:ss ZZ')
print(formatted_time)

Output:

2023-03-14 16:05:09 +00:00

The arrow library’s now() function retrieves the current time, and format() is used to shape it into a string, complete with time zone information.

Bonus One-Liner Method 5: Using dateutil parser

The dateutil module provides powerful extensions to the standard datetime module, including a flexible date parsing function (parse) that can recognize many different date formats automatically.

Here’s an example:

from dateutil import parser

date_string = 'March 14, 2023 at 4:05 PM'
parsed_date = parser.parse(date_string)
print(parsed_date)

Output:

2023-03-14 16:05:00

This snippet parses a string representing a date into a datetime object without needing an explicit format specification, showcasing the flexibility of dateutil.

Summary/Discussion

  • Method 1: datetime module. Straightforward to use. May become verbose with complex formatting requirements.
  • Method 2: time module. Offers traditional C-like date and time formatting. Less suited for newer applications or dealing with a variety of time zones.
  • Method 3: pandas. Ideal for data analysis and manipulation on time series data. Requires importing an extensive library for possibly simple tasks.
  • Method 4: arrow. Simplifies datetime manipulation and provides international support. Additional dependency and may be overkill for basic needs.
  • Method 5: dateutil. Great for parsing dates from strings without known formats. May require additional steps to format the output.