Master Python Time: From Timestamps to Advanced Date Manipulation
This tutorial walks through Python's time and datetime modules, covering timestamps, sleep, local time, formatting, parsing, arithmetic, and the dateutil library for flexible month and year adjustments, with code examples and visual output to illustrate each concept.
Preface
This article summarizes common Python time operations, emphasizing the importance of handling timestamps, sleep, local time, and formatting.
time module
Timestamp
Gets the number of seconds elapsed since 1970‑01‑01 00:00:00 UTC.
import time
timestamp = time.time() # type: float
print(timestamp, type(timestamp))Result shown below:
Sleep
Pauses program execution for a specified number of seconds.
# Sleep 1 second
time.sleep(1)Local time
Retrieves the current local time as a struct_time object.
t = time.localtime() # type: time.struct_time
print(t, type(t))localtime can also accept a timestamp argument.
# Convert timestamp to struct_time
t = time.localtime(1606395685.1878598) # type: time.struct_time
print(t, type(t))Simple time formatting
t = time.ctime() # type: str
print(t, type(t))Result shown below:
time.ctime() can also accept a timestamp.
t = time.ctime(1606395685.1878598) # type: str
print(t, type(t))Time formatting
Date → string (strftime)
t = time.localtime() # type: time.struct_time
t_str = time.strftime("%Y-%m-%d", t) # type: str
print(t_str, type(t_str))String → date (strptime)
t_str = "2020-11-02"
t_time = time.strptime(t_str, "%Y-%m-%d") # type: time.struct_time
print(t_time, type(t_time))Formatting codes
%Y – full year
%m – month (01‑12)
%d – day of month (01‑31)
%H – hour (24‑hour clock, 00‑23)
%M – minute (00‑59)
%S – second (01‑61)
datetime module
Note: datetime and time are different types and should not be mixed.
from datetime import datetimedatetime.today()
t = datetime.today() # type: datetime
print(t, type(t))
print(t.year) # year
print(t.month) # monthdatetime.now()
Similar to today(), returns local time.
t = datetime.now() # type: datetime
print(t, type(t))datetime.utcnow()
Returns the current UTC time.
t = datetime.utcnow() # type: datetime
print("UTC time:", t)Timestamp → datetime
timestamp = time.time()
print(f"timestamp:{timestamp},type:{type(timestamp)}")
t = datetime.fromtimestamp(timestamp)
print(f"t:{t},type:{type(t)}")datetime → string (strftime)
t = datetime.now()
str_datetime = t.strftime("%Y-%m-%d %H:%M:%S")
print(f"String date:{str_datetime},type:{type(str_datetime)}")String → datetime (strptime)
str_datetime = "2020-11-29 22:05:20"
t = datetime.strptime(str_datetime, "%Y-%m-%d %H:%M:%S")
print(f"t:{t},type:{type(t)}")Datetime arithmetic
Adding days is straightforward, but months and years require extra logic.
from datetime import datetime
import datetime as idatetime
t = datetime.now()
print(f"Current time:{t}")
three_day = t + idatetime.timedelta(days=3)
print(f"Three days later:{three_day}")Free datetime arithmetic with dateutil
Install the python-dateutil package to add months or years.
pip install python-dateutil from datetime import datetime
from dateutil.relativedelta import relativedelta
t = datetime.now()
print(f"Current time:{t}")
three_time = t + relativedelta(months=3)
print(f"Three months later:{three_time}")
one_year = t + relativedelta(years=1)
print(f"One year later:{one_year}")
up_year = t + relativedelta(years=-1)
print(f"Same time last year:{up_year}")Conclusion
The article recommends using datetime for most time operations, warns against mixing time and datetime, and highlights the frequent need to convert string dates to datetime objects. The
python-dateutil relativedeltamethods provide convenient month and year arithmetic.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Python Crawling & Data Mining
Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
