Formatting Date and Time in Python

Formatting Date and Time in Python

Python provides powerful formatting options for dates and times using the strftime() method and parsing using strptime() method.

from datetime import *

# Create a datetime object for 2010, January 1st at 10:20:30
dt1 = datetime(2010, 1, 1, 10, 20, 30)

# Display the datetime object (output shown in the image)
# datetime.datetime(2010, 1, 1, 10, 20, 30)

# Format the datetime object using specific directives
dt1.strftime('%d %B, %A %Y. %H:%M:%S')

# Format the datetime object using alternative directives
dt1.strftime('%-d %b, %a %y. %H:%M:%S')
# The string to be converted
str1 = '10 Jan 2015, 10:15:30'

# Check the type of the variable (output shown in the image)
# type(str1)
# <class 'str'>

# Convert the string (str1) into a datetime object (dt2)
# The format string ('%d %b %Y, %H:%M:%S') exactly matches the structure of str1
dt2 = datetime.strptime(str1, '%d %b %Y, %H:%M:%S')

# Display the resulting datetime object (output shown in the image)
# datetime.datetime(2015, 1, 10, 10, 15, 30)

1. Basic Formatting with strftime()

Date Formatting

python

from datetime import date, datetime

# Current date
today = date.today()
print("Date Formatting Examples:")
print(f"Default: {today}")
print(f"YYYY-MM-DD: {today.strftime('%Y-%m-%d')}")
print(f"MM/DD/YYYY: {today.strftime('%m/%d/%Y')}")
print(f"DD-MM-YYYY: {today.strftime('%d-%m-%Y')}")
print(f"Full month: {today.strftime('%B %d, %Y')}")
print(f"Abbr month: {today.strftime('%b %d, %Y')}")
print(f"Day name: {today.strftime('%A, %B %d, %Y')}")

# Output:
# Default: 2023-12-25
# YYYY-MM-DD: 2023-12-25
# MM/DD/YYYY: 12/25/2023
# DD-MM-YYYY: 25-12-2023
# Full month: December 25, 2023
# Abbr month: Dec 25, 2023
# Day name: Monday, December 25, 2023

Time Formatting

python

from datetime import time, datetime

# Current time
now = datetime.now().time()
print("\nTime Formatting Examples:")
print(f"24-hour: {now.strftime('%H:%M:%S')}")
print(f"12-hour: {now.strftime('%I:%M:%S %p')}")
print(f"Short time: {now.strftime('%I:%M %p')}")
print(f"With milliseconds: {now.strftime('%H:%M:%S.%f')}")

# Output:
# 24-hour: 14:30:45
# 12-hour: 02:30:45 PM
# Short time: 02:30 PM
# With milliseconds: 14:30:45.123456

DateTime Formatting

python

from datetime import datetime

current_dt = datetime.now()
print("\nDateTime Formatting Examples:")
print(f"Full: {current_dt.strftime('%Y-%m-%d %H:%M:%S')}")
print(f"Readable: {current_dt.strftime('%A, %B %d, %Y at %I:%M %p')}")
print(f"File friendly: {current_dt.strftime('%Y%m%d_%H%M%S')}")
print(f"SQL format: {current_dt.strftime('%Y-%m-%d %H:%M:%S')}")
print(f"US format: {current_dt.strftime('%m/%d/%Y %I:%M %p')}")
print(f"EU format: {current_dt.strftime('%d/%m/%Y %H:%M')}")

# Output:
# Full: 2023-12-25 14:30:45
# Readable: Monday, December 25, 2023 at 02:30 PM
# File friendly: 20231225_143045
# SQL format: 2023-12-25 14:30:45
# US format: 12/25/2023 02:30 PM
# EU format: 25/12/2023 14:30

2. Common Format Codes

CodeMeaningExample
%YYear with century2023
%yYear without century23
%mMonth (01-12)12
%BFull month nameDecember
%bAbbreviated monthDec
%dDay of month (01-31)25
%AFull weekday nameMonday
%aAbbreviated weekdayMon
%HHour (00-23)14
%IHour (01-12)02
%MMinute (00-59)30
%SSecond (00-59)45
%fMicrosecond123456
%pAM/PMPM
%jDay of year (001-366)359

3. Practical Formatting Examples

Logging Format

python

from datetime import datetime

def log_message(level, message):
    timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    print(f"[{timestamp}] [{level.upper()}] {message}")

# Usage
log_message("info", "Application started")
log_message("error", "Database connection failed")
log_message("warning", "Low disk space")

# Output:
# [2023-12-25 14:30:45] [INFO] Application started
# [2023-12-25 14:30:46] [ERROR] Database connection failed
# [2023-12-25 14:30:47] [WARNING] Low disk space

File Naming Convention

python

from datetime import datetime

def generate_filename(prefix, extension="txt"):
    timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
    return f"{prefix}_{timestamp}.{extension}"

# Usage
files = [
    generate_filename("report"),
    generate_filename("backup", "zip"),
    generate_filename("log", "log")
]

for file in files:
    print(f"Generated: {file}")

# Output:
# Generated: report_20231225_143045.txt
# Generated: backup_20231225_143045.zip
# Generated: log_20231225_143045.log

User-Friendly Display

python

from datetime import datetime, timedelta

def format_relative_time(dt):
    now = datetime.now()
    diff = now - dt
    
    if diff.days == 0:
        if diff.seconds < 60:
            return "Just now"
        elif diff.seconds < 3600:
            return f"{diff.seconds // 60} minutes ago"
        else:
            return f"{diff.seconds // 3600} hours ago"
    elif diff.days == 1:
        return "Yesterday"
    elif diff.days < 7:
        return f"{diff.days} days ago"
    else:
        return dt.strftime('%B %d, %Y')

# Test with different times
test_times = [
    datetime.now() - timedelta(minutes=5),
    datetime.now() - timedelta(hours=2),
    datetime.now() - timedelta(days=1),
    datetime.now() - timedelta(days=3),
    datetime.now() - timedelta(days=10)
]

print("Relative Time Formatting:")
for time in test_times:
    formatted = format_relative_time(time)
    print(f"{time} -> {formatted}")

4. Parsing Strings with strptime()

Basic Parsing

python

from datetime import datetime

# Parse different date formats
date_strings = [
    "2023-12-25",
    "12/25/2023",
    "25-12-2023 14:30:45",
    "December 25, 2023",
    "25 Dec 2023 02:30 PM"
]

formats = [
    '%Y-%m-%d',
    '%m/%d/%Y',
    '%d-%m-%Y %H:%M:%S',
    '%B %d, %Y',
    '%d %b %Y %I:%M %p'
]

print("String to DateTime Parsing:")
for date_str, fmt in zip(date_strings, formats):
    parsed_dt = datetime.strptime(date_str, fmt)
    print(f"'{date_str}' -> {parsed_dt}")

Advanced Parsing Examples

python

from datetime import datetime

def parse_flexible_date(date_string):
    """Try multiple date formats"""
    formats = [
        '%Y-%m-%d',
        '%m/%d/%Y',
        '%d-%m-%Y',
        '%B %d, %Y',
        '%b %d, %Y',
        '%Y%m%d',
        '%d/%m/%Y %H:%M:%S',
        '%m/%d/%Y %I:%M %p'
    ]
    
    for fmt in formats:
        try:
            return datetime.strptime(date_string, fmt)
        except ValueError:
            continue
    
    raise ValueError(f"Unable to parse date: {date_string}")

# Test with various date strings
test_dates = [
    "2023-12-25",
    "12/25/2023",
    "25-12-2023",
    "December 25, 2023",
    "Dec 25, 2023",
    "20231225",
    "25/12/2023 14:30:45",
    "12/25/2023 02:30 PM"
]

print("Flexible Date Parsing:")
for date_str in test_dates:
    try:
        parsed = parse_flexible_date(date_str)
        print(f"✓ '{date_str}' -> {parsed}")
    except ValueError as e:
        print(f"✗ {e}")

5. Custom Formatting Functions

Multi-language Date Formatting

python

from datetime import datetime

class DateFormatter:
    def __init__(self, language='en'):
        self.language = language
        self.months_en = {
            1: 'January', 2: 'February', 3: 'March', 4: 'April',
            5: 'May', 6: 'June', 7: 'July', 8: 'August',
            9: 'September', 10: 'October', 11: 'November', 12: 'December'
        }
        self.months_es = {
            1: 'Enero', 2: 'Febrero', 3: 'Marzo', 4: 'Abril',
            5: 'Mayo', 6: 'Junio', 7: 'Julio', 8: 'Agosto',
            9: 'Septiembre', 10: 'Octubre', 11: 'Noviembre', 12: 'Diciembre'
        }
    
    def format_custom(self, dt, format_type='long'):
        if self.language == 'en':
            months = self.months_en
        else:
            months = self.months_es
        
        if format_type == 'long':
            return f"{months[dt.month]} {dt.day}, {dt.year}"
        elif format_type == 'short':
            return f"{dt.month}/{dt.day}/{dt.year}"
        elif format_type == 'numeric':
            return f"{dt.year}-{dt.month:02d}-{dt.day:02d}"

# Usage
formatter_en = DateFormatter('en')
formatter_es = DateFormatter('es')
current_dt = datetime.now()

print("Multi-language Formatting:")
print(f"English long: {formatter_en.format_custom(current_dt, 'long')}")
print(f"Spanish long: {formatter_es.format_custom(current_dt, 'long')}")
print(f"Short: {formatter_en.format_custom(current_dt, 'short')}")
print(f"Numeric: {formatter_en.format_custom(current_dt, 'numeric')}")

Template-based Formatting

python

from datetime import datetime
import re

class TemplateFormatter:
    def __init__(self):
        self.templates = {
            'log': '[{date} {time}] {message}',
            'file': '{prefix}_{date}_{time}.{ext}',
            'display': 'Today is {weekday}, {month} {day}, {year}',
            'sql': '{year}-{month:02d}-{day:02d} {hour:02d}:{minute:02d}:{second:02d}'
        }
    
    def format(self, template_name, dt, **kwargs):
        template = self.templates.get(template_name)
        if not template:
            raise ValueError(f"Unknown template: {template_name}")
        
        # Extract date components
        components = {
            'date': dt.strftime('%Y-%m-%d'),
            'time': dt.strftime('%H:%M:%S'),
            'year': dt.year,
            'month': dt.month,
            'day': dt.day,
            'hour': dt.hour,
            'minute': dt.minute,
            'second': dt.second,
            'weekday': dt.strftime('%A'),
            'month_name': dt.strftime('%B')
        }
        
        # Add custom kwargs
        components.update(kwargs)
        
        # Format the template
        return template.format(**components)

# Usage
formatter = TemplateFormatter()
current_dt = datetime.now()

print("Template-based Formatting:")
print(formatter.format('log', current_dt, message='System started'))
print(formatter.format('file', current_dt, prefix='backup', ext='zip'))
print(formatter.format('display', current_dt))
print(formatter.format('sql', current_dt))

6. Complete Example: Event Formatter

python

from datetime import datetime, timedelta

class EventFormatter:
    @staticmethod
    def format_event_summary(event_name, start_dt, end_dt):
        """Format event information in a user-friendly way"""
        
        # Date formatting
        if start_dt.date() == end_dt.date():
            # Same day event
            date_str = start_dt.strftime('%A, %B %d, %Y')
            time_str = f"{start_dt.strftime('%I:%M %p')} - {end_dt.strftime('%I:%M %p')}"
        else:
            # Multi-day event
            date_str = f"{start_dt.strftime('%b %d')} to {end_dt.strftime('%b %d, %Y')}"
            time_str = f"Starts: {start_dt.strftime('%I:%M %p')}"
        
        # Duration
        duration = end_dt - start_dt
        hours = duration.total_seconds() / 3600
        
        return f"""
Event: {event_name}
Date: {date_str}
Time: {time_str}
Duration: {hours:.1f} hours
"""
    
    @staticmethod
    def format_calendar_entry(event_name, dt, reminder_minutes=0):
        """Format for calendar applications"""
        reminder_time = dt - timedelta(minutes=reminder_minutes)
        
        return f"""
BEGIN:VEVENT
SUMMARY:{event_name}
DTSTART:{dt.strftime('%Y%m%dT%H%M%S')}
DTEND:{(dt + timedelta(hours=1)).strftime('%Y%m%dT%H%M%S')}
REMINDER:{reminder_time.strftime('%Y%m%dT%H%M%S')}
END:VEVENT
""".strip()

# Usage
event_formatter = EventFormatter()

# Create test events
meeting_start = datetime(2023, 12, 26, 14, 0, 0)
meeting_end = datetime(2023, 12, 26, 15, 30, 0)

conference_start = datetime(2023, 12, 27, 9, 0, 0)
conference_end = datetime(2023, 12, 28, 17, 0, 0)

print("Event Formatting Examples:")
print(event_formatter.format_event_summary("Team Meeting", meeting_start, meeting_end))
print(event_formatter.format_event_summary("Tech Conference", conference_start, conference_end))
print(event_formatter.format_calendar_entry("Team Meeting", meeting_start, 15))

Key Takeaways:

  1. Use strftime() to convert datetime objects to formatted strings
  2. Use strptime() to convert formatted strings to datetime objects
  3. Learn common format codes like %Y%m%d%H%M%S
  4. Create custom formatters for specific application needs
  5. Handle multiple formats when parsing user input

These formatting techniques are essential for displaying dates and times in user-friendly ways and for parsing date strings from various sources!

Similar Posts

  • recursive function

    A recursive function is a function that calls itself to solve a problem. It works by breaking down a larger problem into smaller, identical subproblems until it reaches a base case, which is a condition that stops the recursion and provides a solution to the simplest subproblem. The two main components of a recursive function…

  • Global And Local Variables

    Global Variables In Python, a global variable is a variable that is accessible throughout the entire program. It is defined outside of any function or class. This means its scope is the entire file, and any function can access and modify its value. You can use the global keyword inside a function to modify a…

  • pop(), remove(), clear(), and del 

    pop(), remove(), clear(), and del with 5 examples each, including slicing where applicable: 1. pop([index]) Removes and returns the item at the given index. If no index is given, it removes the last item. Examples: 2. remove(x) Removes the first occurrence of the specified value x. Raises ValueError if not found. Examples: 3. clear() Removes all elements from the list, making it empty. Examples: 4. del Statement Deletes elements by index or slice (not a method, but a…

  • Python Nested Lists

    Python Nested Lists: Explanation & Examples A nested list is a list that contains other lists as its elements. They are commonly used to represent matrices, tables, or hierarchical data structures. 1. Basic Nested List Creation python # A simple 2D list (matrix) matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9]…

  •  List operators,List Traversals

    In Python, lists are ordered, mutable collections that support various operations. Here are the key list operators along with four basic examples: List Operators in Python 4 Basic Examples 1. Concatenation (+) Combines two lists into one. python list1 = [1, 2, 3] list2 = [4, 5, 6] combined = list1 + list2 print(combined) # Output: [1, 2, 3,…

  • Class06,07 Operators, Expressions

    In Python, operators are special symbols that perform operations on variables and values. They are categorized based on their functionality: ⚙️ 1. Arithmetic Operators ➕➖✖️➗ Used for mathematical operations: Python 2. Assignment Operators ➡️ Assign values to variables (often combined with arithmetic): Python 3. Comparison Operators ⚖️ Compare values → return True or False: Python…

Leave a Reply

Your email address will not be published. Required fields are marked *