Python Date and Time Manipulation Tutorial
This tutorial explains how to retrieve the current timestamp, format specific dates, convert between strings and datetime objects, perform time indexing with pandas, and execute time arithmetic and offsets in Python using datetime, pandas, and dateutil libraries.
This article demonstrates how to work with dates and times in Python using the datetime module, pandas , and dateutil , covering retrieval of the current timestamp, formatting, conversion, indexing, and arithmetic operations.
1. Get the current date and time
Return the current date and time:
from datetime import datetime
print(datetime.now())Return the current year, month, and day separately:
from datetime import datetime
print(datetime.now().year)
print(datetime.now().month)
print(datetime.now().day)Return the current weekday (1‑7) and ISO calendar week:
from datetime import datetime
# weekday (Monday=1)
print(datetime.now().weekday() + 1)
# ISO calendar (year, week number, weekday)
print(datetime.now().isocalendar())2. Format a specific date and time
from datetime import datetime
# Show only the date part
print(datetime.now().date())
# Show only the time part
print(datetime.now().time())
# Custom format using strftime
print(datetime.now().strftime('%Y-%m-%d'))
print(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))3. Convert between string and datetime
Convert a datetime object to a string:
from datetime import datetime
now = datetime.now()
print(type(str(now)))Parse a string into a datetime object using dateutil.parser :
from dateutil.parser import parse
str_time = "2020-03-27"
print(type(parse(str_time)))4. Time indexing
import pandas as pd
import numpy as np
index = pd.DatetimeIndex([
'2018-01-01','2018-01-02','2018-01-03','2018-01-04','2018-01-05',
'2018-01-06','2018-01-07','2018-01-08','2018-01-09','2018-01-10'
])
data = pd.DataFrame(np.arange(1,11), columns=['num'], index=index)
print(data)
# Data for the year 2018
print(data["2018"])
# Data for January 2018
print(data["2018-01"])
# Data from 2018-01-01 to 2018-01-05
print(data["2018-01-01":"2018-01-05"])5. Time arithmetic
Difference between two datetime objects:
from datetime import datetime
cha = datetime(2018,5,21,19,50) - datetime(2018,5,18,20,30)
print(cha)
print(cha.days) # days component
print(cha.seconds) # seconds component
print(cha.seconds/3600) # convert to hoursTime offset using timedelta :
from datetime import timedelta, datetime
date = datetime(2018,5,18,20,32)
# Add one day
print(date + timedelta(days=1))
# Add 60 seconds
print(date + timedelta(seconds=60))
# Subtract one day
print(date - timedelta(days=1))
# Subtract 60 seconds
print(date - timedelta(seconds=60))Offset using pandas date offsets:
import pandas as pd
from pandas.tseries.offsets import Day, Hour, Minute
from datetime import timedelta, datetime
date = datetime(2018,5,18,20,32)
# Add one day
print(date + Day(1))
# Add one hour
print(date + Hour(1))
# Add ten minutes
print(date + Minute(10))Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
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.