How do I get the current time in Python?

To get the current time in Python, you can use the datetime or time modules. Here are the most common methods with examples:

1. Using datetime (Recommended for Human-Readable Time)

The datetime module provides a clean way to fetch and format the current time.

Basic Usage:

from datetime import datetime

current_time = datetime.now().time()
print(current_time)  # Output: 15:30:45.123456 (hours:minutes:seconds.microseconds)

Formatted Time:

formatted_time = datetime.now().strftime("%H:%M:%S")
print(formatted_time)  # Output: 15:30:45 (24-hour format)

UTC Time:

utc_time = datetime.utcnow().strftime("%H:%M:%S")
print(utc_time)  # Output: 19:30:45 (UTC time if local time is 15:30:45 EDT)

2. Using time Module (Lower-Level Control)

The time module is useful for timestamps or simple time formatting.

Unix Timestamp (Seconds Since Epoch):

import time

timestamp = time.time()
print(timestamp)  # Output: 1696782645.123456 (float)

Formatted Local Time:

local_time = time.strftime("%H:%M:%S", time.localtime())
print(local_time)  # Output: 15:30:45

3. Time Zones with zoneinfo (Python 3.9+)

For time-zone-aware times:

from datetime import datetime
from zoneinfo import ZoneInfo

# Get time in a specific time zone
ny_time = datetime.now(ZoneInfo("America/New_York")).strftime("%H:%M:%S")
print(ny_time)  # Output: 15:30:45 (EDT)

tokyo_time = datetime.now(ZoneInfo("Asia/Tokyo")).strftime("%H:%M:%S")
print(tokyo_time)  # Output: 04:30:45 (next day JST)

Key Formatting Codes

CodeMeaningExample
%HHour (24-hour)15
%IHour (12-hour)03
%MMinute30
%SSecond45
%fMicroseconds123456
%pAM/PMPM

Examples

12-Hour Format with AM/PM:

print(datetime.now().strftime("%I:%M:%S %p"))  # Output: 03:30:45 PM

Date and Time Together:

print(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))  # Output: 2023-10-08 15:30:45

Milliseconds:

print(datetime.now().strftime("%H:%M:%S.%f")[:-3])  # Output: 15:30:45.123 (truncates to 3 decimals)

Summary

  • Use datetime for human-readable time and formatting.
  • Use time for timestamps or simple formatting.
  • Use zoneinfo (Python 3.9+) for time-zone-aware times.

Let me know if you need more specific examples!

Leave a Reply

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