w3resource

Python: Convert a string to datetime

Python datetime: Exercise-3 with Solution

Write a Python program to convert a string to datetime.

Sample Solution:

Python Code:

# Import the datetime class from the datetime module
from datetime import datetime

# Parse the given date string 'Jul 1 2014 2:43PM' into a datetime object
# using the specified format '%b %d %Y %I:%M%p'
date_object = datetime.strptime('Jul 1 2014 2:43PM', '%b %d %Y %I:%M%p')

# Print the parsed datetime object
print(date_object) 

Output:

2014-07-01 14:43:00 

Explanation:

In the exercise above,

  • The code imports the "datetime" class from the "datetime" module.
  • Parsing the Date string:
    • It then uses the "datetime.strptime()" method to parse the given date string 'Jul 1 2014 2:43PM' into a datetime object.
    • The format of the input date string is specified as '%b %d %Y %I:%M%p', which indicates the month abbreviated (%b), day of the month (%d), year (%Y), hour in 12-hour format (%I), minute (%M), and AM/PM indicator (%p).
  • Printing Results:
    • Finally, it prints the parsed datetime object using the "print()" function.

Flowchart:

Flowchart: Python program to convert a string to datetime.

Python Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Python program to determine whether a given year is a leap year.
Next: Write a Python program to get the current time.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.