- 1 1. Fundamentals to Know Before Handling Dates and Strings in Python
- 2 2. [String to Date] Creating a Date Object Using strptime()
- 3 3. [Date to String] How to Freely Convert Formats Using strftime()
- 4 4. Techniques for Mutual Conversion with ISO 8601 Format
- 5 5. Handy Techniques for Handling Dates
- 5.1 Using timedelta to Add and Subtract Dates
- 5.2 Getting Today’s, Yesterday’s, and Tomorrow’s Dates
- 5.3 Comparing Dates and Calculating the Difference (in Days)
- 5.4 How to Obtain and Determine Specific Days of the Week
- 5.5 Determining Leap Years and Automatic End-of-Month Calculation (Supplement)
- 5.6 Summary
- 6 6. Frequently Asked Questions (FAQ)
- 6.1 Q1. Why does a ValueError occur with strptime()?
- 6.2 Q2. Why are the days of the week displayed in English instead of Japanese?
- 6.3 Q3. Can you convert Japanese dates that include “AM” and “PM”?
- 6.4 Q4. What is the difference between datetime.now() and datetime.today()?
- 6.5 Q5. I cannot convert ISO strings with timezones. What should I do?
- 6.6 Note: What If the Japanese Locale Doesn’t Work Properly on Windows?
- 6.7 Summary
1. Fundamentals to Know Before Handling Dates and Strings in Python
When handling dates and times in Python, the most fundamental module is the “datetime
module”. This article explains in detail how to convert between dates and strings, but first, let’s organize the basic concepts and classes that you should know beforehand.
What is the datetime
in Python’s Standard Library?
In Python, the standard library module datetime
is provided for handling dates and times. It requires no additional installation and can be used immediately, which is a key feature. By using this module, you can perform a wide range of operations such as obtaining the current time, date arithmetic, format conversions, comparisons, and more.
First, let’s check the basic import methods.
import datetime
Alternatively, you can import only the necessary classes as shown below.
from datetime import datetime, date, time, timedelta
Commonly Used Classes and Their Differences
The datetime
module has multiple classes, but the ones most closely related to the conversion between dates and strings are mainly the following three.
datetime.date Class
This is a class that represents year, month, and day information. Time is not included.
d = datetime.date(2025, 4, 7)
print(d) # Output: 2025-04-07
datetime.time Class
This is a class that holds only time-related information, such as hours, minutes, and seconds. It does not include dates.
t = datetime.time(14, 30, 0)
print(t) # Output: 14:30:00
datetime.datetime Class
This is the most versatile class, capable of handling both date (year, month, day) and time (hour, minute, second).
dt = datetime.datetime(2025, 4, 7, 14, 30)
print(dt) # Output: 2025-04-07 14:30:00
This class is most commonly used for converting between strings and dates.
Getting the Current Date and Time with datetime.now()
By using the now()
method of the datetime.datetime
class, you can easily obtain the current date and time.
from datetime import datetime
now = datetime.now()
print(now) # Example: 2025-04-07 13:45:12.345678
The datetime
object obtained in this way can be converted to a string or generated from a string using strftime()
and strptime()
, which will be introduced later.
Summary
In this section, we explained the overview of the datetime
module, which is the most fundamental for handling dates and times in Python, and the differences between its representative classes. In the next section, we will finally focus on “converting strings to dates” and introduce the specific usage of strptime()
.
2. [String to Date] Creating a Date Object Using strptime()
In Python, to convert a string representing a date to a datetime
object, you use the strptime()
method. This is an abbreviation for “string parse time” and is a function that parses the string to recognize it as a date.
In this chapter, we will explain step by step from basic usage to methods for supporting Japanese notation and error handling.
strptime()
Basic Usage and List of Format Specifiers
Basic Syntax
from datetime import datetime
date_string = '2025-04-07'
dt = datetime.strptime(date_string, '%Y-%m-%d')
print(dt) # Output: 2025-04-07 00:00:00
strptime()
takes two arguments like the following:
- First argument: The string to be parsed (e.g., ‘2025-04-07’)
- Second argument: The format of that string (e.g., ‘%Y-%m-%d’)
Commonly Used Format Specifiers
Specifier | Meaning | Example |
---|---|---|
%Y | Year (4 digits) | 2025 |
%y | Year (2 digits) | 25 |
%m | Month (2 digits) | 04 |
%d | Day (2 digits) | 07 |
%H | Hour (24-hour) | 14 |
%M | Minute | 30 |
%S | Second | 59 |
%A | Weekday (English) | Monday |
%p | AM/PM | AM |
Another Example: Conversion Including Date and Time
date_string = '2025-04-07 14:30:00'
dt = datetime.strptime(date_string, '%Y-%m-%d %H:%M:%S')
print(dt) # Output: 2025-04-07 14:30:00
How to Handle Date Strings in Japanese Notation?
To handle common Japanese formats like “April 7, 2025” or “April 07, 2025 (Mon)”, customize the format as follows.
Example of Parsing a String with Japanese Year-Month-Day
date_string = '2025-04-07'
dt = datetime.strptime(date_string, '%Y-%m-%d')
print(dt) # Output: 2025-04-07 00:00:00
Strings containing Japanese weekday names cannot be handled by the basic strptime()
For example, a string like “April 7, 2025 (Mon)” will cause an error when used with strptime()
alone. This is because Python’s strptime()
depends on the locale and does not support Japanese weekdays by default.
In this case, the following countermeasures are available:
- Remove unnecessary Japanese day-of-week parts from the string and then pass to
strptime()
- Utilize external libraries (e.g.,
kanji_to_time
, etc.)
Common Errors and Their Solutions: ValueError
The most common error encountered when using strptime()
is the following.
ValueError: time data '2025/04/07' does not match format '%Y-%m-%d'
What is the cause of this error?
This occurs because the actual format of the string does not match the specified format.
For example, if you want to process a date such as '2025/04/07'
, you need to match the format to slashes as follows.
date_string = '2025/04/07'
dt = datetime.strptime(date_string, '%Y/%m/%d')
Troubleshooting Tips
- Check delimiters (such as -, /, spaces, etc.)
- Whether it is zero-padded (e.g., ’04’ vs ‘4’)
- Whether it does not contain extraneous information that cannot be processed by
strptime()
, such as day of the week, etc.
3. [Date to String] How to Freely Convert Formats Using strftime()
When handling dates in Python, there are many situations where you want to convert a datetime
object to a string in a specific format. In such cases, the strftime()
method is very convenient.
In this chapter, we will explain the basic usage of strftime()
, commonly used format specifiers, and how to display Japanese days of the week and month names.
Basic Usage of strftime()
Syntax and Simple Usage Examples
from datetime import datetime
dt = datetime(2025, 4, 7, 14, 30)
formatted = dt.strftime('%Y-%m-%d %H:%M:%S')
print(formatted) # Output: 2025-04-07 14:30:00
strftime()
is an abbreviation for “string format time“, and it converts a datetime
object to a string in the specified format.
Common Format Specifiers (Reproduced)
Specifier | Meaning | Example |
---|---|---|
%Y | Year (4 digits) | 2025 |
%m | Month (2 digits) | 04 |
%d | Day (2 digits) | 07 |
%H | Hour (24-hour) | 14 |
%M | Minute | 30 |
%S | Second | 00 |
%A | Weekday (English) | Monday |
%a | Weekday (abbreviated) | Mon |
%p | AM/PM | PM |
Practical Example: Freely Customizing the Format
Display Year/Month/Day with Slash Separators
dt = datetime(2025, 4, 7)
formatted = dt.strftime('%Y/%m/%d')
print(formatted) # Output: 2025/04/07
Convert to Japanese-style Format
dt = datetime(2025, 4, 7)
formatted = dt.strftime('%Y-%m-%d')
print(formatted) # Output: 2025-04-07
Detailed Display with Time
dt = datetime(2025, 4, 7, 14, 30)
formatted = dt.strftime('%Y-%m-%d %H:%M')
print(formatted) # Output: 2025-04-07 14:30
If You Want to Display the Day of the Week in Japanese
You can use strftime('%A')
to display the day of the week, but by default, it is displayed in English. If you want to display it in Japanese, you need to change the locale (language settings).
Example Using the locale Module (for UNIX/Linux Environments)
import locale
from datetime import datetime
locale.setlocale(locale.LC_TIME, 'en_US.UTF-8')
dt = datetime(2025, 4, 7)
formatted = dt.strftime('%B %d, %Y (%A)')
print(formatted) # Output: April 7, 2025 (Monday)
Notes
- In Windows environments,
'ja_JP.UTF-8'
may not be available. - Because it is environment-dependent, avoid hardcoding in web apps or distributed code.
- If prioritizing stability, there is also a method to map weekdays yourself using a dictionary.
weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
weekday = weekdays[dt.weekday()]
print(f"{dt.strftime('%Y-%m-%d')} ({weekday})")
Summary
In this chapter, we introduced how to convert datetime
objects to strings using strftime()
, along with examples. The ability to freely customize the output format is very useful in various scenarios, such as visualizing date data or log output.
In the next chapter, we will explain the mutual conversion with the standardized date format “ISO 8601 format.”

4. Techniques for Mutual Conversion with ISO 8601 Format
When integrating data between systems or communicating via APIs, it is common to exchange dates and times in “ISO 8601 format”. In Python as well, conversion to and from this format is one of the very important operations.
This chapter explains how to convert to and from ISO 8601 format in Python, and how to handle strings with time zones.
What is the ISO 8601 Format?
The ISO 8601 format is the date and time notation rules established by the International Organization for Standardization (ISO). It is represented in formats like the following:
2025-04-07T14:30:00
- Insert “T” between the date and time
- 24-hour format
- Timezone information (e.g.,
+09:00
orZ
) may also be included
This format is widely used in various data formats such as JSON and XML, REST APIs, log files, and more.
isoformat()
to Convert Dates to ISO Format Strings
Python’s datetime
objects come with a convenient method called isoformat()
.
Usage Example
from datetime import datetime
dt = datetime(2025, 4, 7, 14, 30)
iso_str = dt.isoformat()
print(iso_str) # Output: 2025-04-07T14:30:00
Fine adjustments are also possible with arguments
# Display up to milliseconds
print(dt.isoformat(timespec='milliseconds')) # 2025-04-07T14:30:00.000
# Obtain only the date
print(dt.date().isoformat()) # 2025-04-07
fromisoformat()
to Convert ISO Format to datetime Object
Conversely, to generate a datetime
object from a string in ISO 8601 format, use fromisoformat()
.
Usage Example
iso_str = '2025-04-07T14:30:00'
dt = datetime.fromisoformat(iso_str)
print(dt) # Output: 2025-04-07 14:30:00
It is highly intuitive and supported in Python 3.7 and later.
How to Handle ISO Strings Containing Timezone Information
The standard fromisoformat()
may not handle cases that include timezone information (e.g., +09:00
or Z
) properly. In such cases, using a third-party library allows for more flexible handling.
Recommended Library: dateutil.parser
pip install python-dateutil
Usage Example
from dateutil import parser
iso_str = '2025-04-07T14:30:00+09:00'
dt = parser.parse(iso_str)
print(dt) # Output: 2025-04-07 14:30:00+09:00
In this way, ISO strings with time zones can also be parsed accurately.
Note: Differences between UTC and Z Notation
Z
is an abbreviation meaning “Zulu Time (UTC)”.2025-04-07T14:30:00Z
represents the time in UTC (Coordinated Universal Time).
Python’s standard fromisoformat()
does not support Z
notation, so using dateutil.parser
is recommended.
Summary
The ISO 8601 format is essential for exchanging date and time data. In Python, you can easily perform conversions using isoformat()
and fromisoformat()
, but when handling strings with time zones, using the external library dateutil
is highly effective.
In the next chapter, we will introduce advanced techniques useful for practical work, such as date calculations, comparisons, and finding differences.
5. Handy Techniques for Handling Dates
When handling dates and times, in addition to simply converting formats, processes such as comparing dates and adding or subtracting dates are also commonly used.
In this chapter, we will explain practical techniques that are useful in real-world work, focusing on the datetime
module.
Using timedelta
to Add and Subtract Dates
To calculate dates such as “one day later,” “one week ago,” “30 days later,” etc., use the datetime.timedelta
class.
Calculating One Day After and One Day Before
from datetime import datetime, timedelta
today = datetime(2025, 4, 7)
tomorrow = today + timedelta(days=1)
yesterday = today - timedelta(days=1)
print(tomorrow) # Output: 2025-04-08 00:00:00
print(yesterday) # Output: 2025-04-06 00:00:00
Addition and subtraction by hour is also possible
dt = datetime(2025, 4, 7, 14, 30)
plus_2_hours = dt + timedelta(hours=2)
print(plus_2_hours) # Output: 2025-04-07 16:30:00
Getting Today’s, Yesterday’s, and Tomorrow’s Dates
Another very common pattern is to obtain relative dates based on the current date and time.
from datetime import datetime, timedelta
now = datetime.now()
today = now.date()
yesterday = today - timedelta(days=1)
tomorrow = today + timedelta(days=1)
print(f"Today: {today}")
print(f"Yesterday: {yesterday}")
print(f"Tomorrow: {tomorrow}")
With this, you can easily implement features like daily reports and schedulers.
Comparing Dates and Calculating the Difference (in Days)
It is also possible to calculate the chronological relationship between two dates or their differences (such as number of days, time, etc.).
Date Comparison (Greater/Lesser Relationship)
d1 = datetime(2025, 4, 7)
d2 = datetime(2025, 4, 10)
print(d1 < d2) # Output: True
Calculating the Difference (Using timedelta)
delta = d2 - d1
print(delta.days) # Output: 3
In this way, the difference is obtained as a timedelta
object, and details can be retrieved from its .days
or .seconds
attributes.
How to Obtain and Determine Specific Days of the Week
To get the day of the week from a date or to check if it’s a specific day of the week, use .weekday()
or .isoweekday()
.
Method | Output (e.g., Monday) |
---|---|
.weekday() | 0 (= Monday) |
.isoweekday() | 1 (= Monday) |
d = datetime(2025, 4, 7) # Monday
print(d.weekday()) # Output: 0
print(d.isoweekday()) # Output: 1
How to Display Days of the Week in Japanese (Mapping Using a Dictionary)
weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
weekday_jp = weekdays[d.weekday()]
print(f"{d.strftime('%Y/%m/%d')} ({weekday_jp})")
Determining Leap Years and Automatic End-of-Month Calculation (Supplement)
import calendar
# Determine if it's a leap year
print(calendar.isleap(2024)) # Output: True
# Get the last day of the month
last_day = calendar.monthrange(2025, 4)[1]
print(last_day) # Output: 30
Summary
In this chapter, we introduced methods for date addition and subtraction, comparison, difference calculation, and weekday determination that frequently appear in professional work. In particular, processing utilizing timedelta
is highly versatile and is a fundamental skill for date processing that you should keep in mind.
In the next chapter, we will compile Frequently Asked Questions (FAQ) related to the content explained so far and provide information to help resolve any doubts.
6. Frequently Asked Questions (FAQ)
We’ve summarized common stumbling points for beginners when handling dates and strings in Python, in a FAQ format. Please use this for troubleshooting and reinforcing your understanding.
Q1. Why does a ValueError occur with strptime()?
A. It is highly likely that the format does not match.
In strptime()
, if the string and the specified format differ by even one character, it will result in an error.
Example: Invalid Cases
from datetime import datetime
date_string = '2025/04/07'
# Format is set to "-" but it's inconsistent
dt = datetime.strptime(date_string, '%Y-%m-%d')
# → ValueError occurs
Example of correction:
dt = datetime.strptime(date_string, '%Y/%m/%d')
Other possible causes include the following:
- Presence or absence of zero padding (e.g., 04 and 4)
- Extraneous characters (e.g., days of the week or spaces)
- Unsupported formats (e.g., Japanese ‘AM/PM’ etc.)
Q2. Why are the days of the week displayed in English instead of Japanese?
A. strftime('%A')
depends on the locale (language settings).
Since Python’s default settings use English, the weekdays retrieved using %A
will be Monday
and so on.
Solution 1: Use the locale
Module (UNIX/Linux Systems)
import locale
from datetime import datetime
locale.setlocale(locale.LC_TIME, 'ja_JP.UTF-8')
dt = datetime(2025, 4, 7)
print(dt.strftime('%A')) # Output: Monday
Solution 2: Mapping Weekdays to Japanese Using a Dictionary (Environment-Independent)
weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
print(weekdays[dt.weekday()]) # Output: Monday
Q3. Can you convert Japanese dates that include “AM” and “PM”?
A. It is not supported in Python’s standard strptime()
.
For example, strings like 'April 7, 2025, 2:30 PM'
will cause an error with the standard strptime()
.
How to Handle:
- Manually convert ‘AM/PM’ to time using regular expressions, etc.
- Use of external libraries (e.g.,
dateparser
)
pip install dateparser
import dateparser
s = 'April 7, 2025 2:30 PM'
dt = dateparser.parse(s)
print(dt) # Output: 2025-04-07 14:30:00
Q4. What is the difference between datetime.now()
and datetime.today()
?
A. They are essentially the same (datetime.datetime
).
from datetime import datetime
print(datetime.now()) # Get the current date and time
print(datetime.today()) # Similarly, get the current date and time
Both return the current local time. While there are precise differences outlined in the Python documentation, for typical use cases, they behave identically, so you can treat them as the same without issue.
Q5. I cannot convert ISO strings with timezones. What should I do?
A. datetime.fromisoformat()
does not support some strings with time zones.
Example: 2025-04-07T14:30:00+09:00
etc.
Solution: Use dateutil.parser.parse()
from dateutil import parser
s = '2025-04-07T14:30:00+09:00'
dt = parser.parse(s)
print(dt) # Output: 2025-04-07 14:30:00+09:00
By using the dateutil
library, you can flexibly handle strings with time zones as well.
Note: What If the Japanese Locale Doesn’t Work Properly on Windows?
If locale.setlocale(locale.LC_TIME, 'ja_JP.UTF-8')
doesn’t work, the locale name for Windows is something like Japanese_Japan.932
.
locale.setlocale(locale.LC_TIME, 'Japanese_Japan.932')
However, due to potential differences depending on the environment, dictionary mapping is more reliable.
Summary
In the FAQ, we explain common errors and confusing points with specific examples. If you can resolve these doubts, you should gain considerable confidence in handling dates and strings in Python.