strptime(): parses a string representing a date and/or time and converts it into a datetime object

strptime() : Returns date object from input string with format details.

Date input

from datetime import datetime

str_date = "2021-8-25" # Date as string
dt = datetime.strptime(str_date, "%Y-%m-%d")

print(type(dt)) # <class 'datetime.datetime'>
print(dt) # 2021-08-25 00:00:00

Example

from datetime import datetime

str_date = "28021985" # Date as string
dt = datetime.strptime(str_date, "%d%m%Y")

print(dt.year, dt.month, dt.day) # 1985 2 28

# Adding format
print(dt.strftime("%Y-%m-%d")) # 1985-02-28

Date with time

from datetime import datetime

str_date = "2021/8/25 13:45:53" # Date as string
dt = datetime.strptime(str_date, "%Y/%m/%d %H:%M:%S")

print(dt) # 2021-08-25 13:45:53

Using Microsecond

str_date = "2021/8/25 13:45:53 341789" # Date as string
dt = datetime.strptime(str_date, "%Y/%m/%d %H:%M:%S %f")

print(dt) # 2021-08-25 13:45:53.341789

Wrong format

In case format is not matching , then we will get ValueError.
str_date='2021-8-25' # date as string 
dt=datetime.strptime(str_date,'%Y/%m/%d')
ValueError: time data '2021-8-25' does not match format '%Y/%m/%d'

List of format codes used with strptime() is here

Handling Timezones with strptime()

When parsing date strings that include timezone information, we can use the %Z directive. However, it's important to note that strptime() may not recognize all timezone abbreviations, leading to potential issues.

from datetime import datetime

date_string = "2025-02-07 16:39:23 IST"
dt = datetime.strptime(date_string, "%Y-%m-%d %H:%M:%S %Z")
print(dt)

In this example, if the timezone abbreviation 'IST' is not recognized, a ValueError will be raised. To handle such cases, we can replace the timezone abbreviation with a UTC offset before parsing:

from datetime import datetime

date_string = "2025-02-07 16:39:23 IST"
# Replace 'IST' with '+0530' for the UTC offset
date_string = date_string.replace("IST", "+0530")
dt = datetime.strptime(date_string, "%Y-%m-%d %H:%M:%S %z")
print(dt)

Here, we replace 'IST' with its corresponding UTC offset '+0530' and use the %z directive to parse it. This approach ensures accurate parsing of timezone information.

Parsing ISO 8601 Date Strings

ISO 8601 is a widely used format for date and time representations. To parse an ISO 8601 date string, we can use the appropriate format directives:

from datetime import datetime

iso_date_string = "2025-02-07T16:39:23"
dt = datetime.strptime(iso_date_string, "%Y-%m-%dT%H:%M:%S")
print(dt)

In this example, the 'T' character separates the date and time components. We include it directly in the format string to match the input.

Handling Optional Microseconds

When parsing date strings where the microseconds component is optional, we can define a function to handle both cases:

from datetime import datetime

def parse_date(date_string):
    try:
        return datetime.strptime(date_string, "%Y-%m-%d %H:%M:%S.%f")
    except ValueError:
        return datetime.strptime(date_string, "%Y-%m-%d %H:%M:%S")

date_with_microseconds = "2025-02-07 16:39:23.123456"
date_without_microseconds = "2025-02-07 16:39:23"

print(parse_date(date_with_microseconds))
print(parse_date(date_without_microseconds))

This function attempts to parse the date string with microseconds first. If it fails, it retries without microseconds. This approach ensures flexibility in handling both formats.

Common Pitfalls and Best Practices

  • Matching Format Strings: Ensure that the format string exactly matches the input date string. Mismatched formats will raise a ValueError.
  • Handling Timezones: Be cautious with timezone abbreviations, as strptime() may not recognize all of them. Using UTC offsets is a more reliable approach.
  • Validating Input: Always validate the input date strings to ensure they conform to the expected format before parsing.

Conclusion

By understanding and addressing these advanced scenarios, we can enhance our use of the strptime() function to handle a wider range of date and time parsing requirements effectively.


All Date Objects strftime()
Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com







    Python Video Tutorials
    Python SQLite Video Tutorials
    Python MySQL Video Tutorials
    Python Tkinter Video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer