杰瑞科技汇

python time strftime

Of course! The time.strftime() function in Python is a powerful and commonly used tool for formatting dates and times into strings. It's part of the standard time module.

python time strftime-图1
(图片来源网络,侵删)

Let's break it down in detail.

What is strftime()?

The name strftime stands for "string format time". Its job is to take a struct_time object (which represents a point in time) and convert it into a string based on a format code you provide.


The Basic Syntax

import time
time.strftime(format_code[, t])
  • format_code (string): This is the most important part. It's a string containing special codes (called format codes) that start with a . These codes are replaced with the corresponding time value. All other characters in the string are left as-is.
  • t (optional): A struct_time object to format. If you omit this argument, strftime() will format the current local time.

The Most Common Format Codes

Here are the format codes you'll use most frequently. It's helpful to have these memorized or bookmarked.

Code Meaning Example Output (for today)
%Y Year with century as a decimal number. 2025
%y Year without century as a zero-padded decimal. 23
%m Month as a zero-padded decimal number. 09
%B Month as full locale name. September
%b Month as abbreviated locale name. Sep
%d Day of the month as a zero-padded decimal. 05
%A Weekday as full locale name. Tuesday
%a Weekday as abbreviated locale name. Tue
%w Weekday as a decimal number, where 0 is Sunday. 2
%H Hour (24-hour clock) as a zero-padded decimal. 14
%I Hour (12-hour clock) as a zero-padded decimal. 02
%M Minute as a zero-padded decimal. 30
%S Second as a zero-padded decimal. 05
%p Locale’s equivalent of either AM or PM. PM
%f Microsecond as a decimal number, zero-padded. 123456
%j Day of the year as a zero-padded decimal. 248
%U Week number of the year (Sunday as the first day of the week). 36
%W Week number of the year (Monday as the first day of the week). 36
%c Locale’s appropriate date and time representation. Tue Sep 5 14:30:05 2025
%x Locale’s appropriate date representation. 09/05/23
%X Locale’s appropriate time representation. 14:30:05
A literal character.

Practical Examples

Let's see it in action. We'll start with the current time.

python time strftime-图2
(图片来源网络,侵删)

Example 1: Formatting the Current Time

import time
# Get the current time in a struct_time format
current_time = time.localtime()
# Define the format string
format_string = "%Y-%m-%d %H:%M:%S"
# Format the time
formatted_time = time.strftime(format_string, current_time)
print(f"Current time: {current_time}")
print(f"Formatted as: {formatted_time}")
# Example with a more complex format
another_format = "Today is %A, %B %d, %Y. The time is %I:%M %p."
another_formatted = time.strftime(another_format, current_time)
print(f"\nAnother format: {another_formatted}")

Output (will vary depending on when you run it):

Current time: time.struct_time(tm_year=2025, tm_mon=9, tm_mday=5, tm_hour=14, tm_min=30, tm_sec=5, tm_wday=1, tm_yday=248, tm_isdst=0)
Formatted as: 2025-09-05 14:30:05
Another format: Today is Tuesday, September 05, 2025. The time is 02:30 PM.

Example 2: Formatting a Specific Time

You can also create a struct_time object for a specific date and time and then format it. This is useful for logging or generating reports.

import time
# Create a struct_time for January 1st, 2025, 10:30:00 AM
# Note: tm_isdst=-1 means the library should determine if DST is in effect.
# For a fixed time, it's often set to 0 (not in DST).
specific_time = time.struct_time((2025, 1, 1, 10, 30, 0, 0, 1, 0))
# Format it as a standard log timestamp
log_format = "%Y-%m-%dT%H:%M:%S"
log_entry = time.strftime(log_format, specific_time)
print(f"Log entry: {log_entry}")
# Format it for a user-friendly display
user_format = "On %A, %B %d, %Y at %I:%M %p"
user_display = time.strftime(user_format, specific_time)
print(f"User display: {user_display}")

Output:

Log entry: 2025-01-01T10:30:00
User display: On Monday, January 01, 2025 at 10:30 AM

Important Considerations

Locale

The output of codes like %A, %B, %p, %c, %x, and %X depends on your system's locale settings.

python time strftime-图3
(图片来源网络,侵删)
import time
import locale
# Set the locale to German (Germany)
# You might need to install the locale first on Linux/macOS
# On Windows, it's usually available.
try:
    locale.setlocale(locale.LC_TIME, 'de_DE.UTF-8')
    current_time = time.localtime()
    german_format = "%A, der %d. %B %Y"
    print(f"German format: {time.strftime(german_format, current_time)}")
    # Set the locale to French (France)
    locale.setlocale(locale.LC_TIME, 'fr_FR.UTF-8')
    french_format = "%A le %d %B %Y"
    print(f"French format: {time.strftime(french_format, current_time)}")
    # Reset to the system's default
    locale.setlocale(locale.LC_TIME, '')
    print(f"Default format: {time.strftime('%A, %B %d %Y', current_time)}")
except locale.Error:
    print("The specified locale is not available on this system.")

time.strftime() vs. datetime.strftime()

For new code, especially when you are already working with dates, the datetime module is often preferred. It's more object-oriented and generally easier to work with.

datetime module approach (often recommended):

from datetime import datetime
# Get the current time as a datetime object
now = datetime.now()
# The format codes are the same!
format_string = "%Y-%m-%d %H:%M:%S"
# The strftime method is a method of the datetime object itself
formatted_time = now.strftime(format_string)
print(f"Formatted with datetime: {formatted_time}")

Why prefer datetime?

  • Object-Oriented: You can easily perform arithmetic (add days, subtract hours).
  • Timezone Aware: datetime has excellent built-in support for timezones via the pytz library or the standard zoneinfo module (Python 3.9+). The time module's timezone handling is more complex.
  • More Flexible: It's easier to create datetime objects from strings and vice-versa.

When to use time.strftime?

  • When you are working with legacy code that uses the time module.
  • When you need a very lightweight solution and don't require the advanced features of datetime.
  • When you are directly interfacing with a C library that uses struct_time.

Summary

Feature time.strftime() datetime.datetime.strftime()
Module time datetime
Input struct_time object datetime object
Common Use Quick timestamp formatting, legacy code General-purpose date/time manipulation
Strengths Simple, lightweight Object-oriented, good for math/timezones

For most new Python projects, start with the datetime module. But if you just need to quickly format the current time into a string, time.strftime() is perfectly fine and gets the job done.

分享:
扫描分享到社交APP
上一篇
下一篇