As full-stack developers, we regularly wrestle with handling time in our code. While computers track time precisely in numeric formats, humans understand time relatively using language. Bridging this gap requires converting raw timestamps programmatically into human-readable time strings.
Python offers compelling libraries to parse, process, and format timestamps. By leveraging these tools effectively, we can build intuitive applications optimized for how users comprehend time.
This comprehensive guide explores best practices for formatting human-readable times in Python. We will dive deep into:
- Getting and processing current times
- Converting timestamps to readable strings
- Handling timezones
- Advanced date/time calculations
- Analyzing time series
- Visualizing timestamps
- Real-world applications
Follow along for tips to boost your Python time manipulation skills.
Current Time in Python
The Python time module provides simple access to current time values via two core functions:
time.time() – Returns current UTC time as a floating point epoch timestamp
import time
print(time.time()) # 1677443075.96858
current_time_ms = round(time.time()*1000) # Millisecond precision
time.localtime() – Converts timestamp into struct_time with breakdown of date/time details
import time
current_time = time.localtime()
print(current_time)
# time.struct_time(tm_year=2023, tm_mon=2, tm_mday=27, tm_hour=15, tm_min=11, tm_sec=53, tm_wday=0, tm_yday=58, tm_isdst=0)
These core functions enable retrieving machine-readable time values for current processing in Python code.
However, these raw numeric formats don‘t mean much to users. Next we‘ll explore converting them into human-readable timestamps.
Building Readable Time Strings
Python offers several handy formatting methods through its time, datetime, and global locale modules.
Let‘s examine them in action:
time.ctime()
The simplest approach is time.ctime() to convert a timestamp into a readable string:
import time
current_ts = time.time()
readable_time = time.ctime(current_ts)
print(readable_time)
# Mon Feb 27 15:14:10 2023
ctime() nicely formats the timestamp to contain day name, month text, day number, time, year based on locale‘s preferred order and month names.
However, customization is limited. For more flexibility formatting timestamps in Python, read on!
time.strftime()
The time.strftime() method allows specifying custom format codes to layout timestamp details in any desired string format.
| Code | Meaning | Example |
|---|---|---|
| %Y | Year | 2023 |
| %B | Month name | February |
| %b | Abbreviated month | Feb |
| %d | Day of month | 27 |
| %A | Weekday name | Monday |
| %I | 12-hour clock Hour | 03 |
| %M | Minute | 14 |
| %p | AM/PM | PM |
Let‘s use some common codes:
from time import strftime
formatted_time = strftime("%d %B %Y, %A at %I:%M %p", time.localtime())
print(formatted_time)
# 27 February 2023, Monday at 03:14 PM
This enables complete control over timestamp formatting for human readability.
datetime Module
The Python datetime module contains datetime and timedelta objects enabling complex date/time calculations:
from datetime import datetime
now = datetime.now() # Current date/time
today = now.date() # Just date
time = now.time() # Just time
# Date math
yesterday = now - timedelta(days = 1)
last_week = now - timedelta(weeks = 1)
print(yesterday) # 2023-02-26 15:14:10
print(last_week) # 2023-02-20 15:14:10
We can also format datetimes easily:
from datetime import datetime
now = datetime.now()
formatted_time = now.strftime("%B %d, %Y %I:%M %p")
print(formatted_time)
# February 27, 2023 03:14 PM
The datetime module is invaluable for handling dates and times in Python.
timezones – UTC vs Local Time
A key consideration when processing times is timezone handling.
Times can be represented in UTC (coordinated universal time) or local system time. UTC does not account for geographic timezones.
Python stores and parses times in UTC by default. So we need to consciously convert between UTC and local times.
The tzlocal module helps bridge this gap:
from datetime import datetime
from tzlocal import get_localzone # $ pip install tzlocal
utc_now = datetime.utcnow() # Current UTC time
local_tz = get_localzone() # Local timezone
local_now = utc_now.astimezone(local_tz) # Convert UTC -> Local
print(utc_now) # 2023-02-27 20:14:10
print(local_now) # 2023-02-27 12:14:10 (Local time)
This handles timezone conversion. Always consider the user‘s timezone when processing and displaying timestamps in apps!
Pandas Datetime Capabilities
Pandas provides integrated capabilities for handling datetimes and time series data.
Converting strings to datetimes:
import pandas as pd
date_strings = [‘2023-01-01‘, ‘2023-02-01‘]
date_times = pd.to_datetime(date_strings)
print(date_times)
#0 2023-01-01
#1 2023-02-01
#dtype: datetime64[ns]
Powerful time series handling:
dates = [‘2023-01-01‘, ‘2023-02-01‘]
time_series = pd.Series([100, 200], index=pd.to_datetime(dates))
print(time_series)
#2023-01-01 100
#2023-02-01 200
#dtype: int64
Pandas integrates nicely for analyzing timestamped data sets.
Complex Datetime Calculations
Performing precise calculations on dates and times is cumbersome. Thankfully, Python datetime and dateutil modules help handle advanced datetime math cleanly.
Common capabilities enabled:
- Date difference comparisons
- Adding/subtracting dates
- Date range generations
- Weekday/weekend detection
- Start/end date finding for date ranges
- Custom offsets (business days, holidays, etc)
Let‘s demonstrate some advanced date calculations:
from datetime import datetime, timedelta
from dateutil.relativedelta import relativedelta
now = datetime(2023, 2, 1) # Custom fixed date
one_week_ago = now - timedelta(weeks=1)
print(one_week_ago) # 2023-01-25 00:00:00
eight_business_days_ago = now + relativedelta(weekday=FR(-8)) # 8 weekdays ago
print(eight_business_days_ago) # 2023-01-19 00:00:00
next_friday = now + relativedelta(weekday=FR)
print(next_friday) # 2023-02-03 00:00:00
first_day_last_month = now + relativedelta(day=1, months=-1)
print(first_day_last_month) # 2023-01-01
Datutil enables working with datetimes in more human, business intuitive ways vs just basic numeric offsets. This helps build enterprise-grade applications for processing times.
Analyzing Time Series Data
Understanding trends over time is critical for data-driven analysis and decisions. Python‘s Pandas library provides a TimeSeries data structure to simplify time-based analysis.
Let‘s walk through a real-world time series analysis example using Python:
import pandas as pd
from datetime import datetime
datetime_today = datetime.now()
dates = [datetime_today - timedelta(days=x) for x in range(30)]
values = [round(random.random()*100,2) for x in range(30)]
time_series = pd.Series(values, index=dates, name=‘Daily Sales‘)
print(time_series.head())
#2023-02-26 15:14:10 41.63
#2023-02-27 15:14:10 69.96
#2023-02-28 15:14:10 12.83
#2023-03-01 15:14:10 78.78
#2023-03-02 15:14:10 34.63
We can process this time series data flexibly:
Aggregate by date period
monthly_sales = time_series.resample(‘M‘).mean()
print(monthly_sales)
Visualize trends
import matplotlib.pyplot as plt
time_series.plot()
plt.title("Daily Sales Historical")
plt.ylabel("Sales ($)")

Robust capabilities for analyzing real-world time series with Python.
Best Practices for Readable Times
Now that we‘ve covered capabilities for handling human readable times, let‘s discuss some best practices:
Use Relative Times
Leverage relativedelta to describe times against now rather than exact timestamps:
- "3 weeks ago" vs "January 31st, 2023"
Localize Timezones
Convert all timestamps to the user‘s timezone:
- Ensure accurate, localized times
Format Strings by Usage
Long format for display, short format for data:
- Display: March 5, 2023
- Data: 2023-03-05
Consider Language/Locale
Present appropriate textual formats per user language and locale settings.
Adhering to these principles will optimize Python timestamp representations for how humans intuitively understand time.
Real-world Examples
Let‘s explore some real applications demonstrating the importance of human readable timestamps:
User Action Logging
Recording user actions like logins with exact readable timestamps:
2023-02-27T11:14:32.015Z - JohnDoe logged in
Server Uptime Monitoring
Checking and alerting on duration servers have been running:
Server online for 14 days, 11:05:46
Article Publishing
Showing dates and times for published content:
Published Feb 27, 2023 at 11:20 AM
Data Warehouse Tables
Storing transaction history with timestamps, but formatted minimally:
2023-02-05T14:00:10Z
In all these cases, Python‘s datetime handling brings readable, localized times to apps!
Summary
Python offers exceptional support for manipulating dates and times – a common challenge in programming. Its robust standard libraries paired with external packages provide complete coverage for not only handling raw numeric timestamps but also tailoring readable semantic time strings optimized for human users. By mastering these versatile date/time functions within Python, we can build more intuitive applications and data tools for efficiently working with temporal data.


