What’s New ?

The Top 10 favtutor Features You Might Have Overlooked

Read More

How to Convert String to DateTime in Python? (with code)

  • Mar 10, 2023
  • 7 Minutes Read
  • Why Trust Us
    We uphold a strict editorial policy that emphasizes factual accuracy, relevance, and impartiality. Our content is crafted by top technical writers with deep knowledge in the fields of computer science and data science, ensuring each piece is meticulously reviewed by a team of seasoned editors to guarantee compliance with the highest standards in educational content creation and publishing.
  • By Abrar Ahmed
How to Convert String to DateTime in Python? (with code)

The motivation behind developing any kind of program is to make the common man's life simpler. Therefore our codes should also be able to hand dates and times effectively. A method of storing and performing operations on dates and times is by converting dates and times into strings. Once they are converted into strings, normal string operations can be performed on them.

The two modules that are used to perform these conversions are the DateTime module and the Time module. Let us know about these modules in detail.

DateTime module

The datetime module is a standard Python library, which offers classes for dealing with dates and times. The module defines the following primary classes: date, time, datetime, timedelta, and tzinfo.

The date is stored using date objects (year, month, and day). The day and time are stored in time objects (hours, minutes, seconds, and microseconds). The data from both date and time objects are combined in datetime objects.

The duration or difference between two dates or times is represented via timedelta objects. It enables mathematical operations using dates and times, such as the addition or subtraction of a certain amount of days, seconds, or microseconds. The datetime class uses tzinfo objects to represent time in a time zone-aware manner.

The datetime module also offers useful functions, such as datetime.now() and datetime.today(), which return the current date and time, as well as datetime.utcnow(), which delivers the current UTC date and time. These functions are available in addition to the standard classes and functions.

Numerous functions are available in the datetime module for extracting dates and times from strings and formatting them as strings.

Time module

Python's time module has functions for working with time-related data, such as converting between various time representations, determining how much time has passed since a specific operation, and sleeping for a predetermined period.

The module has a variety of functions for handling time in seconds, including time(), which returns the current time in seconds since the epoch (the instant in time when the first second of a given year happened), and sleep(), which pauses execution for a predetermined amount of seconds.

Additionally, the module has conversion functions between seconds and other time representations, such as local time, which is represented by a tuple of nine values that includes the year, month, day, hour, minute, second, weekday, day of the year, and daylight saving time flag. To convert seconds since the epoch to various time formats, use the gmtime() and local time () methods.

The time module also offers a struct time class, which can be used to express time more understandably in addition to the fundamental time functions. This class offers properties for gaining access to the various parts of a time representation, including the day, month, and year.

How to convert date time to string?

The datetime and time modules in Python can be used to represent dates and times. In many applications, the task of converting date and time objects to strings is frequent. The strptime() method, the strftime() method with custom format codes, the strftime() method with the date and time classes, and more ways are available to carry out this conversion.

The most popular technique for converting date and time objects to strings is strftime(). Both the datetime and time modules offer this option. The format string that is passed as an input to the method tells it how you want the output string to be formatted.

Each element of the date and time, including the year, month, day, hour, minute, and second, is represented by a code in the format string. The percent sign (%) is used in front of these codes. For instance, the following code can be used to turn a datetime object into a string with the format "YYYY-MM-DD":

import datetime

dt = datetime.datetime(2021, 1, 1, 12, 0, 0)

result = dt.strftime("%Y-%m-%d")

print(result)

 

Output:

 2021-01-01

 

Strftime() additionally permits the use of unique format codes in addition to conventional ones. By providing the complete format string as an argument, custom format codes can be created. For instance, the following code can be used to turn a datetime object into a string of the format "01 January 2021":

import datetime

dt = datetime.datetime(2021, 1, 1, 12, 0, 0)

result = dt.strftime("%d %B %Y")

print(result)

 

Output:

01 January 2021

 

To convert a string representation of a date and time into a datetime object, use the strptime() function. The date and time are represented as strings in this method's two arguments, together with a format string that indicates the format of the input string. For instance, the following code can be used to convert a text of the format "YYYY-MM-DD" into a datetime object:

import datetime

date_string = "2021-01-01"

result = datetime.datetime.strptime(date_string, "%Y-%m-%d")

print(result)

 

Output:

datetime.datetime(2021, 1, 1, 0, 0)

 

Utilizing the strftime() function with the date and time classes is another technique to convert date and time objects to strings.

The time class represents time information without a date, whereas the date class represents a date (year, month, and day) without time information. The strftime() method of both classes can be used to turn their objects into strings. For instance, the following code can be used to turn a date object into a string with the format "YYYY-MM-DD":

import datetime

date = datetime.date(2021, 1, 1)

result = date.strftime("%Y-%m-%d")

print(result) # 

 

Output:

 2021-01

 

Conclusion

Datetime objects are important to store information about dates and times that are crucial to many applications that computer science engineers build. Here we learned how to convert datetime from string in Python or string to datetime. Happy Learning :)

FavTutor - 24x7 Live Coding Help from Expert Tutors!

About The Author
Abrar Ahmed
An ambivert individual with a thirst for knowledge and passion to achieve. Striving to connect Artificial Intelligence in all aspects of life. I am also an avid coder and partake in coding challenges all the time on Leetcode and CodeChef.