Languages
[Edit]
EN

Python - convert string to datetime

0 points
Created by:
Mark-Rotteveel
537

In this article, we would like to show you how to convert a string into datetime in Python.

Quick solution:

from datetime import datetime

datetime_object = datetime.strptime('Jun 11 2021  8:35PM', '%b %d %Y %I:%M%p')
print(datetime_object)  # 2021-06-11 20:35:00

Where:

  • %b - abbreviated month name,

  • %d - day of the month (01 to 31),

  • %Y - year including the century,

  • %I - hour (01 to 12),

  • %M - minute

  • %p - either am or pm according to the specified value.

Practical example

In this example, we convert a string into a datetime object with specified format using strptime() method.

from datetime import datetime

date_string = "Jun 11 2021  8:35PM"
date_format = "%b %d %Y %I:%M%p"
datetime_object = datetime.strptime(date_string, date_format)

print(datetime_object)  # 2021-06-11 20:35:00

Output:

2021-06-11 20:35:00
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Python - string (popular problems)

Python - convert string to datetime
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join