Date Manipulation in Python
This article explains date manipulation in Python.
YouTube Video
Date Manipulation in Python
Date manipulation in Python primarily uses the datetime
module. This module provides various classes and functions to manipulate dates and times.
Below are some examples of basic date manipulation using the datetime
module.
Getting Date and Time
You can get the current date and time as follows. datetime.now()
and datetime.today()
return almost the same result, but there can be differences in how they handle time zones.
1from datetime import datetime
2
3# Get the current date and time
4now = datetime.now()
5print(f"Current date and time: {now}")
6
7# Get today's date only
8today = datetime.today()
9print(f"Today's date: {today.date()}")
- This code retrieves and displays the current date and time, as well as just today's date.
Creating Specific Dates and Times
You can create a specific date and time as follows.
1from datetime import datetime
2
3# Create a specific date and time
4specific_date = datetime(2023, 11, 7, 10, 30, 45)
5print(f"Specified date and time: {specific_date}")
- This code creates and displays the specified date and time (November 7, 2023, 10:30:45).
Formatting Dates
Date formatting can be done as follows.
1from datetime import datetime
2
3now = datetime.now()
4
5# Format the date
6formatted_date = now.strftime("%Y-%m-%d %H:%M:%S")
7print(f"Formatted date and time: {formatted_date}")
- This code gets the current date and time, formats it to the specified format using
strftime
, and displays it.
Date format strings
%Y
: Year (4 digits)%m
: Month (01 to 12)%d
: Day (01 to 31)%H
: Hour (00 to 23)%M
: Minute (00 to 59)%S
: Second (00 to 59)
Parsing date strings
You can convert a string representing a date into a datetime
object.
1from datetime import datetime
2
3date_string = "2023-11-07 10:30:45"
4parsed_date = datetime.strptime(date_string, "%Y-%m-%d %H:%M:%S")
5print(f"Parsed date and time: {parsed_date}")
- This code converts a date represented as a string into a
datetime
object usingstrptime()
and displays it.
Date Arithmetic
Date arithmetic can be performed as follows.
1from datetime import datetime, timedelta
2
3now = datetime.now()
4
5# Date for one day later
6tomorrow = now + timedelta(days=1)
7print(f"Date for one day later: {tomorrow}")
8
9# Date for one week ago
10last_week = now - timedelta(weeks=1)
11print(f"Date for one week ago: {last_week}")
12
13# Time for two hours later
14in_two_hours = now + timedelta(hours=2)
15print(f"Time for two hours later: {in_two_hours}")
- This code uses
timedelta
to add or subtract days and times from the current date and time, calculating and displaying the date and time for tomorrow, one week ago, and two hours later.
Handling time zones
You can also handle time zones with the datetime
module.
1from datetime import datetime, timezone, timedelta
2
3# Current UTC time
4utc_now = datetime.now(timezone.utc)
5print(f"Current UTC time: {utc_now}")
6
7# JST (UTC+9)
8jst = timezone(timedelta(hours=9))
9jst_now = datetime.now(jst)
10print(f"Current JST time: {jst_now}")
datetime
returns a 'naive datetime' (without timezone information) by default. You can explicitly handle time zones by using thetimezone
class orzoneinfo
.
The date class and time class
With the datetime
module, you can also handle only dates or only times.
1from datetime import date, time
2
3d = date(2023, 11, 7)
4t = time(10, 30, 45)
5
6print(f"Date only: {d}")
7print(f"Time only: {t}")
- The
date
class handles only dates, and thetime
class handles only times.
Conversion between datetime
and timestamp
Conversion between UNIX timestamps and datetime
objects is possible. Here, a UNIX timestamp refers to the number of seconds elapsed since January 1, 1970.
1from datetime import datetime
2
3now = datetime.now()
4
5# datetime → timestamp
6timestamp = now.timestamp()
7print(f"Timestamp: {timestamp}")
8
9# timestamp → datetime
10restored = datetime.fromtimestamp(timestamp)
11print(f"Restored datetime: {restored}")
- This code converts the current date and time to a UNIX timestamp, then uses the
fromtimestamp()
function to convert that timestamp back to adatetime
object.
Common pitfalls
When using the datetime
module, you should be aware of the following points.
datetime.now()
does not consider time zones, so for internationalization, you need to explicitly usetimezone.utc
.- Be careful not to confuse
%m
(month) and%M
(minute) in format strings.
Summary
The datetime
module also provides many other features for flexible date and time manipulation. Additionally, classes like date
, time
, and timedelta
are available, specialized for specific operations.
Using other libraries also enables more advanced date manipulation. For example, pandas
specializes in handling time series data, while dateutil
is suitable for complex date parsing. Also, the arrow
library is useful too.
You can follow along with the above article using Visual Studio Code on our YouTube channel. Please also check out the YouTube channel.