Code Example: Convert a String to DateTime in Python

Do you want to convert a string to Datetime in Python? This article will discuss how to convert a String to Datetime in Python using strptime().

In Python, there is a DateTime library[1] that has a function or method named strptime() that can be used to convert a string in a date-time format. There is another function named strftime() that can be used to format the string to a proper DateTime value.

How to Convert a String to DateTime Using strptime Function

Let us see in the below code example the usage of strptime function that you can use from the DateTime library of Python for conversion of the string to date.

#importing date libray
from datetime import datetime

#Initializing the String to date and time
giveStringToConvert = "Nov 20 2021 1:57AM"

#Converting String to 
getDateTime =  datetime.strptime(giveStringToConvert, '%b %d %Y %I:%M%p')

print(getDateTime)

Output:

2021-11-20 01:57:00

In the above example, the string is converted to a proper DateTime Format that is stored in a DateTime object, and then we are printing the Object to get the Output.

As per the above code, the second argument can be known as the below mentioned.

  • %b Month as the abbreviated name of the location.
  • %d Day of the month expressed as a decimal number with a zero padding.
  • %Y Year expressed as a integer number with the century (2021).
  • %I Hour (12-hour clock) expressed as a decimal value with zero padding.
  • %M Minute expressed as a decimal value with zero padding.
  • %p The equivalent of either AM or PM in a given locale (PM).

How To Convert Date yyyy-mm-dd Without using Time

The code converted the string to a complete DateTime format. What if you want to convert the same above-mentioned string only as of the date in the yyyy-mm-dd format. Let us see in the below example code how you can do it in Python.

#importing date libray
from datetime import datetime

#Initializing the String to date and time
giveStringToConvert = "Nov 20 2021 1:57AM"

#Converting String to yyyy-mm-dd format
getDateTime =  datetime.strptime(giveStringToConvert, '%b %d %Y %I:%M%p').date()

print(getDateTime)

Output:

2021-11-20

As you can see with the usage of the date() method in the last of the DateTime object provided the date in the yyyy-mm-dd format. Also, if you want to convert the given string to date without time then you can use the above code example.

How To Convert String With Month Name To DateTime Object

You have a String that is containing the date only with the month mentioned as the name as provided in the below example. You can easily convert it to the DateTime object again by using the strptime and you can format it using strftime. Let us see the code example below.

#importing date libray
from datetime import datetime

#Initializing the String to date and time
giveStringToConvert = "Nov 20 2021"

#Converting String to DateTime Object
getDateTime =  datetime.strptime(giveStringToConvert, '%b %d %Y')

print(getDateTime.strftime('%Y-%m-%d'))

Output:

2021-11-20

As you saw in the above code using strftime I was able to format the DateTime Object quickly to my desired date format that I need. Similarly, you can also modify the format the way you need the date to look.

How To Convert month,day,year to month,year with Python

Let us see another example code where you want to convert a string provided as a month, day, year to month, year.

#importing date libray
from datetime import datetime

#Initializing the String to date and time
giveStringToConvert = "Nov 20 2021"

#Converting String to DateTime Object
getDateTime =  datetime.strptime(giveStringToConvert, '%b %d %Y')

#Formating Date to month and year
getDateTime = getDateTime.strftime('%m/%Y')

print(getDateTime)

Output:

11/2021

How To Convert A String To DateTime Object with Timezone Aware

You are having a string that you want to convert to DateTime Object with TimeZone Aware, you can do that using the DateTime method. Let us convert the current time to timezone awareness in the below example code.

#importing date libray
from datetime import datetime, timezone

#Initializing the String to date and time
giveStringToConvert = "Nov 20 2021 2:41AM"

#Converting String to DateTime Object
getDateTime =  datetime.strptime(giveStringToConvert, '%b %d %Y %I:%M%p')

getDateTime = getDateTime.replace(tzinfo=timezone.utc)

print(getDateTime)

Output:

2021-11-20 02:41:00+00:00

To make the DateTime Object as timezone aware I have imported the timezone library and then use the tzinfo and assigned it to a basic timezone as UTC.

Code Example: Convert a String to Datetime in Python

Now your DateTime Object is TimeZone aware time that you can use to convert it to different time zone easily.

How To Convert A String to ISO DateTime In Python

In Python 3, you get a feature to convert a string to an ISO DateTime Object. Return a string containing the date in the ISO 8601 format, YYYY-MM-DD (year, month, and day). Let us see in the below example code for ISO DateTime.

#importing date libray
from datetime import datetime, timezone

#Initializing the String to date and time
giveStringToConvert = "Nov 20 2021 2:41AM"

#Converting String to DateTime Object
getDateTime =  datetime.strptime(giveStringToConvert, '%b %d %Y %I:%M%p')

getDateTime = getDateTime.isoformat()

print(getDateTime)

Output:

2021-11-20T02:41:00

And hence if you want the only date or only time then you can use the Python strip method to strip the DateTime from ‘T’ and you will have two list items one will be the date and the other will be the time.

Code Example: Convert a String to Datetime in Python

Wrap Up

I hope you got the answers related to how to convert a String to DateTime in Python. I have discussed various methods that can occur for this particular problem. Let me know if I have missed or you know some better methods I will be happy to add them here.

If you liked the above tutorial then please follow us on Facebook and Twitter. Let us know the questions and answer you want to cover in this blog.

Further Read:

  1. How Do I Sort A Dictionary By Value In Python
  2. Code Example: How To Add Numbers In A List Python
  3. Python – How To Delete All Files In A Directory
  4. How To Remove Non-alphanumeric Characters From String In Python
  5. How To Multiply Without Using * In Python
  6. How To Add or Append Values To a Set In Python
  7. 4 Ways To List All Subdirectories in a Directory – Python
  8. Dict To list – Convert A Dictionary to a List in Python
  9. Discord.py Bot Add Reaction To a Message Python
  10. Python Get The Minimum Value In Dictionary with Key

Leave a Reply

Your email address will not be published. Required fields are marked *