MC, 2025
Ilustracja do artykułu: Unlocking Python Datetime Formatting: A Comprehensive Cheatsheet

Unlocking Python Datetime Formatting: A Comprehensive Cheatsheet

If you’ve ever worked with dates and times in Python, you know how essential proper formatting is for displaying and manipulating them. The built-in Python `datetime` module is incredibly powerful, but it can be a little tricky to remember all the various formatting codes. That’s why having a Python datetime formatting cheatsheet can be a lifesaver, especially for quick lookups while coding!

In this article, we’re going to walk you through the most commonly used datetime formatting options in Python. Whether you’re displaying a timestamp in your desired format or parsing a date string, this guide will provide you with all the tools you need. By the end, you’ll be able to format Python datetime objects with confidence and ease!

Understanding the Basics: Python Datetime Module

Before diving into formatting codes, let’s quickly review what the `datetime` module offers. This module allows you to work with dates and times in both simple and complex ways, offering tools to create, manipulate, and format datetime objects.

The basic components of the datetime module include:

  • datetime: A combination of date and time (e.g., 2023-04-24 15:30:00).
  • date: Represents the date without the time (e.g., 2023-04-24).
  • time: Represents the time without the date (e.g., 15:30:00).
  • timedelta: Represents the difference between two datetime objects.
  • tzinfo: Handles timezone information.

The most common operation you’ll perform is formatting a `datetime` object into a human-readable string. Python makes this easy with the `strftime()` method, which allows you to format dates and times in a variety of ways.

Python Datetime Formatting Codes

The `strftime()` method uses special format codes to define how the date and time should be displayed. Let’s go through the most frequently used formatting codes and their meanings:

Date Formatting Codes

These are the codes you’ll use when you need to format the date part of a datetime object:

  • %Y: Year with century (e.g., 2023)
  • %y: Two-digit year (e.g., 23 for 2023)
  • %m: Month as a zero-padded decimal number (01-12)
  • %d: Day of the month as a zero-padded decimal number (01-31)
  • %b: Abbreviated month name (e.g., Jan, Feb, Mar)
  • %B: Full month name (e.g., January, February, March)
  • %a: Abbreviated weekday name (e.g., Mon, Tue, Wed)
  • %A: Full weekday name (e.g., Monday, Tuesday, Wednesday)

Time Formatting Codes

These codes are for formatting the time part of a datetime object:

  • %H: Hour (00-23)
  • %I: Hour (01-12)
  • %M: Minute as a zero-padded decimal number (00-59)
  • %S: Second as a zero-padded decimal number (00-59)
  • %p: AM or PM
  • %f: Microsecond as a zero-padded decimal number (000000-999999)
  • %z: UTC offset in the form +HHMM or -HHMM
  • %Z: Time zone name (e.g., UTC, EST)

These formatting codes can be combined to produce any format you need! Let’s take a look at a few examples to see how this works.

Python Datetime Formatting Cheatsheet Examples

1. Simple Date Format

Let’s say you want to display today’s date in the format day/month/year. Here’s how you can do it:

from datetime import datetime

now = datetime.now()
formatted_date = now.strftime("%d/%m/%Y")
print(formatted_date)  # Output: 24/04/2023

In this example, we use the formatting codes %d, %m, and %Y to display the day, month, and year in the desired format.

2. Full Date and Time

If you want to include both the date and time in the format weekday, month day, year at time, you can do it like this:

from datetime import datetime

now = datetime.now()
formatted_datetime = now.strftime("%A, %B %d, %Y at %I:%M %p")
print(formatted_datetime)  # Output: Monday, April 24, 2023 at 03:30 PM

Here, we’re using %A for the full weekday name, %B for the full month name, %d for the day, %Y for the year, %I for the hour (12-hour format), %M for the minute, and %p for AM/PM.

3. Time Only

If you only need the time in a 24-hour format, you can use this:

from datetime import datetime

now = datetime.now()
formatted_time = now.strftime("%H:%M:%S")
print(formatted_time)  # Output: 15:30:00

Here, %H gives you the hour in 24-hour format, %M gives the minutes, and %S gives the seconds.

4. Custom Formats

Python also lets you create custom formats by combining various datetime formatting codes. For example, let’s say you want a timestamp that looks like this: 2023-04-24T15:30:00Z. You can do it as follows:

from datetime import datetime

now = datetime.now()
formatted_timestamp = now.strftime("%Y-%m-%dT%H:%M:%SZ")
print(formatted_timestamp)  # Output: 2023-04-24T15:30:00Z

This format combines the date and time, followed by the letter T (which is commonly used in ISO 8601 format), and ends with Z to denote Zulu time (UTC).

5. Handling Time Zones

If you need to include time zone information in your formatted datetime, you can do so with the %z and %Z codes. Here’s an example that includes the UTC offset:

from datetime import datetime
import pytz

utc_now = datetime.now(pytz.utc)
formatted_utc = utc_now.strftime("%Y-%m-%d %H:%M:%S %z")
print(formatted_utc)  # Output: 2023-04-24 15:30:00 +0000

In this example, we use the %z code to include the UTC offset, which will show as +0000 for UTC time.

Conclusion

With this Python datetime formatting cheatsheet, you now have all the tools you need to format your datetime objects in a variety of ways. Whether you’re working with full date-time stamps or just need the date or time in a custom format, Python’s strftime() method has you covered.

Don’t forget to experiment with these formatting codes and mix them to create the perfect output for your projects. Happy coding!

Komentarze (0) - Nikt jeszcze nie komentował - bądź pierwszy!

Imię:
Treść: