Home » Datetime.Strptime() In Python

Datetime.Strptime() In Python

Datetime.Strptime() In Python

In Python, the datetime.strptime() method is a powerful function used to parse (or read) strings representing dates and times and convert them into datetime objects. It stands for “string parse time”.

strptime() takes two arguments: a string representing the date and time, and a format string specifying the format of the input string.

Syntax


datetime.strptime(date_string, format)

Python
  • date_string: A string representing the date and time.
  • format: A string specifying the format of the input date_string.

Real-Life Example: Parsing Date from a User Input

Let’s say you have a program where users enter their birthdate as a string in the format “YYYY-MM-DD”. You want to convert this string into a datetime object for further processing.


from datetime import datetime

# User input
user_input = input("Enter your birthdate (YYYY-MM-DD): ")

# Parse the input string
birthdate = datetime.strptime(user_input, "%Y-%m-%d")

# Output
print("Parsed birthdate:", birthdate)

Python

In this example, "%Y-%m-%d" is the format string. It specifies that the input string should contain the year (%Y), followed by the month (%m), and the day of the month (%d). When the user enters their birthdate in the specified format, strptime() converts it into a datetime object in Python.

Common Format Codes in Python Strptime():

  • %Y: Year (4 digits)
  • %m: Month (01-12)
  • %d: Day of the month (01-31)
  • %H: Hour (00-23)
  • %M: Minute (00-59)
  • %S: Second (00-59)

Handling Different Date Formats in Python Strptime()


from datetime import datetime

# Date in different formats
date1 = "2023-12-25"
date2 = "Jan 15, 2023"

# Parsing dates
parsed_date1 = datetime.strptime(date1, "%Y-%m-%d")
parsed_date2 = datetime.strptime(date2, "%b %d, %Y")

# Output
print("Parsed date 1:", parsed_date1)
print("Parsed date 2:", parsed_date2)

Python

In this example, strptime() can handle dates in different formats. By specifying the appropriate format string for each input string, it correctly parses the dates into datetime objects in python.

Certainly! Here are a few more examples demonstrating the usage of datetime.strptime() with different format strings:

Example 1: Parsing Date and Time from a String


from datetime import datetime

# Date and time string
date_time_str = '2023-12-25 08:30:00'

# Parse the date and time
parsed_date_time = datetime.strptime(date_time_str, '%Y-%m-%d %H:%M:%S')

# Output
print("Parsed date and time:", parsed_date_time)

Python

This code will output the parsed date and time as a datetime object.

Example 2: Parsing Date without Leading Zeros


from datetime import datetime

# Date string without leading zeros
date_str = '1/15/23'

# Parse the date
parsed_date = datetime.strptime(date_str, '%m/%d/%y')

# Output
print("Parsed date:", parsed_date)

Python

This code will correctly parse the date “January 15, 2023” despite the absence of leading zeros in the month and day.

Example 3: Handling Dates with Different Date Separator


from datetime import datetime

# Date string with a different separator
date_str = '15-Jan-2023'

# Parse the date
parsed_date = datetime.strptime(date_str, '%d-%b-%Y')

# Output
print("Parsed date:", parsed_date)

Python

This code demonstrates parsing a date string with a different separator (‘-‘ instead of ‘/’), showing the flexibility of strptime() in handling various date formats in python.

Example 4: Parsing Time with AM/PM Indicator


from datetime import datetime

# Time string with AM/PM indicator
time_str = '08:30 PM'

# Parse the time
parsed_time = datetime.strptime(time_str, '%I:%M %p')

# Output
print("Parsed time:", parsed_time)

Python

This code will parse the time “8:30 PM” and output it as a datetime object.

These examples showcase the versatility of datetime.strptime() in parsing date and time strings from different formats. By providing the appropriate format string, you can accurately convert various date and time representations into datetime objects for further processing in your Python programs.

Conclusion

The datetime.strptime() method provides a convenient way to parse date and time strings into datetime objects in Python. By specifying the appropriate format string that matches the structure of the input string, you can accurately convert diverse date and time representations into standardized datetime objects. Whether you’re processing user inputs, reading data from files, or working with date strings from various sources, strptime() enables you to efficiently handle date and time parsing tasks in your Python applications. With its simplicity and flexibility, datetime.strptime() is an essential tool for managing date and time data effectively in Python programming.

Frequently Asked Questions

Q1, What happens if the format string provided to datetime.strptime() doesn’t match the format of the input string?

Ans: If the format string does not match the format of the input string, datetime.strptime() will raise a ValueError exception.


Q2. Can datetime.strptime() handle parsing of timezone information?

Ans: No, datetime.strptime() does not handle timezone information. It assumes that the input string represents a date and time in the local timezone unless explicitly specified in the input string.


Q3. Can I parse dates and times with microseconds using datetime.strptime()?

Ans: Yes, you can include %f in the format string to parse microseconds. For example, '%Y-%m-%d %H:%M:%S.%f' can parse dates and times with microseconds.


Q4. Is datetime.strptime() case-sensitive for month and weekday names?

Ans: No, datetime.strptime() is not case-sensitive for month and weekday names. It can parse both upper and lower case representations of month and weekday names.