Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Python program to display various datetime formats
The datetime module in Python provides powerful classes for manipulating dates and times. The strftime() method allows you to format dates and times in various ways using format codes.
Basic Date Formatting
Let's start with common date formats using format codes ?
import datetime
today = datetime.date.today()
print("Day of the week:", today.strftime("%A"))
print("Week number:", today.strftime("%W"))
print("Day of the year:", today.strftime("%j"))
Day of the week: Monday Week number: 47 Day of the year: 332
Various Date and Time Formats
Here are more formatting options with complete date and time ?
import datetime
now = datetime.datetime.now()
print("Full date and time:", now.strftime("%A, %B %d, %Y %I:%M:%S %p"))
print("Short date:", now.strftime("%m/%d/%Y"))
print("ISO format:", now.strftime("%Y-%m-%d"))
print("Time 24-hour:", now.strftime("%H:%M:%S"))
print("Time 12-hour:", now.strftime("%I:%M:%S %p"))
print("Month name:", now.strftime("%B"))
print("Abbreviated month:", now.strftime("%b"))
print("Abbreviated weekday:", now.strftime("%a"))
Full date and time: Monday, November 28, 2023 02:30:45 PM Short date: 11/28/2023 ISO format: 2023-11-28 Time 24-hour: 14:30:45 Time 12-hour: 02:30:45 PM Month name: November Abbreviated month: Nov Abbreviated weekday: Mon
Common Format Codes
| Format Code | Description | Example |
|---|---|---|
%A |
Full weekday name | Monday |
%a |
Abbreviated weekday name | Mon |
%B |
Full month name | November |
%b |
Abbreviated month name | Nov |
%d |
Day of month (01-31) | 28 |
%j |
Day of year (001-366) | 332 |
%W |
Week number (00-53) | 47 |
%Y |
4-digit year | 2023 |
%H |
Hour 24-hour format | 14 |
%I |
Hour 12-hour format | 02 |
Practical Example
Create a formatted timestamp for logging or file naming ?
import datetime
now = datetime.datetime.now()
# For logging
log_format = now.strftime("[%Y-%m-%d %H:%M:%S] INFO: Process completed")
print(log_format)
# For file naming
file_format = now.strftime("backup_%Y%m%d_%H%M%S.txt")
print("Filename:", file_format)
# User-friendly format
friendly_format = now.strftime("Today is %A, %B %d, %Y at %I:%M %p")
print(friendly_format)
[2023-11-28 14:30:45] INFO: Process completed Filename: backup_20231128_143045.txt Today is Monday, November 28, 2023 at 02:30 PM
Conclusion
The strftime() method provides flexible date and time formatting using format codes. Use %A for weekday names, %j for day of year, and %W for week numbers. Combine multiple codes to create custom formats for logging, file naming, or user display.
Advertisements
