- Free Python 3 Course
- Control Flow
- Exception Handling
- Python Programs
- Python Projects
- Python Interview Questions
- Python Database
- Data Science With Python
- Machine Learning with Python
- Write an Interview Experience
- Share Your Campus Experience
- Generating random strings until a given string is generated
- Python | Ways to remove numeric digits from given string
- Python | Find longest consecutive letter and digit substring
- Iterate over words of a String in Python
- Python program to verify that a string only contains letters, numbers, underscores and dashes
- Python program for removing i-th character from a string
- Python program to split and join a string
- Python | Find all possible substrings after deleting k characters
- Python Program to Accept the Strings Which Contains all Vowels
- Python | Split string into list of characters
- Python program to check if a string has at least one letter and one number
- Find length of a string in python (6 ways)
- Python | Split string in groups of n consecutive characters
- How to Remove Letters From a String in Python
- Python – Filter Tuples with All Even Elements
- Python – Time Strings to Seconds in Tuple List
- Python | Check if substring is part of List of Strings
- Python | Split string on Kth Occurrence of Character
- Python | Check if substring present in string

Convert string to DateTime and vice-versa in Python
A common necessity in many programming applications is dealing with dates and times. Python has strong tools and packages that simplify handling date and time conversions. This article will examine how to effectively manipulate and format date and time values in Python by converting Strings to Datetime objects and back. We will cover the article into two parts:
- Python Convert String to Datetime
Python Convert Datetime to String
Python convert string to datetime , python string to datetime using datetime.strptime().
The Strptime() is available in Datetime and time modules and is used for Date-Time Conversion. This function changes the given string of Datetime into the desired format.
Example: The program defines a function that converts a date and time represented as string to datetime object using the desired format. The conversion is performed using the datetime.strptime() method.
Python String to Datetime Using Dateutil Module
The Dateutil is a third-party module. The parsing of dates in any string format is supported by the Dateutil module. Internal facts about current world time zones are provided by this module. Parse() can be used to convert a Python string to date-time format. The only parameter used is the string.
Example: The program imports the dateutil library’s parser module, for converting string to datetime which has a function for parsing date and time strings. The format is recognized automatically by the Parser.parse() function, which transforms the string “Jun 23 2022 07:31PM” into a DateTime object.
Python Datetime to String u sing Time.strftime
Python strftime() function is present in datetime and time modules to create a string representation based on the specified format string. We are using this method to convert datetime to string in Python. Another similar function is available in the Python time module which converts a tuple or struct_time object to a string as specified by the format argument.
Example: The program converts the Datetime to String Python and imports the Python time module, which offers functions for handling time-related activities. The convert() function takes a tuple datetime_str as input, transforms it to a timestamp using time.mktime(), and then formats the timestamp into a string representation using the format “%b%d%Y%r” that was supplied.
Time Complexity: O(1) Auxiliary Space: O(1)
Python Datetime to String using Datetime
Bring the datetime module to convert Datetime to String Python Using the specified date and time, create a datetime object. Create a format string that outlines the formatting requirements for the datetime object. To create a string in the desired format, use the datetime object’s strftime() method. The format string is the argument for the strftime() function.
Example: The program imports the datetime module, which gives Python programmers access to classes for working with dates and times. The provided date and time values, March 14, 2022, at 15:30:00, are used to generate a datetime object. The datetime object is transformed into a string representation based on the format string using the strftime() method.
Please Login to comment...
Improve your coding skills with practice.

- Learn Python
- Python Lists
- Python Dictionaries
- Python Strings
- Python Functions
- Learn Pandas & NumPy
- Pandas Tutorials
- Numpy Tutorials
- Learn Data Visualization
- Python Seaborn
- Python Matplotlib
Python strptime: Converting Strings to DateTime
- April 4, 2023 April 4, 2023

In this post, you’ll learn how to convert a Python string to a date, using the datetime module’s strptime function . I’ve been working with Python for years now, and one thing that never ceases to amaze me is the sheer power and flexibility of this language. I’ve used it for everything from web development to data analysis, and today, I want to share my experience with one of the most useful functions when it comes to working with dates and times : the Python strptime() function.
If you’ve ever had to convert a string to a datetime object, you know it can be a bit of a headache. But worry not, because I’m here to guide you through the process with some handy tips and tricks I’ve picked up along the way.
By the end of this tutorial, you’ll have learned the following:
- The basics of the Python strptime function and how to use it effectively
- How to specify the correct format for successful string-to-datetime conversion
- Techniques for handling timezones and milliseconds with strptime
So grab a cup of your favorite beverage, and let’s dive into the world of Python datetime conversion together!
Are you looking to convert a datetime object to a string? Check out how to use the Python strftime function to convert a datetime object to a string .
Table of Contents
The Quick Answer: Use datetime’s strptime Function to Convert a String to Datetime
Let’s dive in!
Understanding the Python strptime Function
Python’s datetime module comes with the standard Python library, meaning you don’t need to worry about installing it. The datetime module comes with three main object types: date , time , and datetime .
The Python strptime function is a part of the datetime module, and its purpose is to convert a string representing a date and/or time into a datetime object.
The function requires two arguments:
- date_string : The date string you want to convert, and
- format : The format string that specifies the expected format of the date string.

Before we dive into some examples, let’s take a look at the most common formatting strings available for use with the strptime function. Here’s a handy table to help you understand the various format codes:
Are you looking to convert a Pandas column to datetime? Check out how to use the Pandas to_datetime function which converts an entire column to datetime .
How to Convert a String to datetime in Python
Now that we have a better understanding of the format codes, let’s put the Python strptime function to work! In order to convert a string to datetime in Python, you need to pass in the string and the format code into the strptime() function .
In the examples below, I have provided two different use cases. One that’s a simple string, representing only a date and another that includes time as well.
We can see how easy it is to format our strings into datetime objects! The format codes makes it very intuitive to convert strings into dates and times.
Remember, specifying the correct format is crucial for successful conversion. If the format doesn’t match the date string, you’ll encounter errors. But don’t worry, as we move forward in this tutorial, we’ll discuss how to troubleshoot and handle such issues.
How to Convert a String to date in Python
In order to convert a string to a date in Python, you can use the .strptime() function and then chain the .date() method onto the resulting datetime object. Because the function generates a datetime object, you need to add an additional step to return only a date.
The benefit of this approach is that you only need to learn one function, rather than two! Let’s take a look at an example, where we’ll convert a string that contains a date and time and return only the date object:
In the code block above, we first converted the string to a datetime object using the strptime() function. Then, we chained on the .date() method, which returns a date object, containing only the date information.
How to Convert a String to time in Python
Similar to converting a string to a time in Python, you need to first convert the string to a datetime object with the strptime() function, then apply the .time() method to convert the object to a time object.
Let’s take a look at how we can do this by using the same string as an example:
We can see from the code block above that we first converted our string (which contains a date and time) to a datetime object. Then, by applying the .time() method, we were able to convert it to a time object. This process can be quite helpful, since you don’t need to worry about using Python to first strip the text.
Handling Timezones with Python strptime Timezone
Working with timezones can be a bit tricky, but it’s an essential skill to master, especially when dealing with data from different sources or users across the globe. I’ve had my fair share of experiences working on projects where incorrect timezone handling led to inaccurate data analysis and reporting. Trust me, it’s not a situation you want to find yourself in!
To avoid such issues, it’s crucial to understand how to work with timezones using the Python strptime function. By properly handling timezone information during string-to-datetime conversion, you can ensure that your data analysis and manipulation tasks are accurate and reliable, no matter where your data comes from.
Let’s dive into some examples to better understand how to handle timezones with the strptime function:
In these examples, we’ve demonstrated how to convert date and time strings that include timezone information into datetime objects.
The first example uses the timezone abbreviation (EST), while the second example uses the timezone offset (-0500). By specifying the correct format codes (%Z for timezone abbreviation and %z for timezone offset), we can successfully convert the strings to datetime objects with their respective timezone information.
In my experience, properly handling timezones is crucial when working with data from international users, IoT devices, or any scenario where timestamps are recorded in different timezones. By mastering the strptime function and its usage with timezones, you’ll be well-equipped to tackle any timezone-related challenges that come your way.
How to Fix: ValueError: time data does not match format
One of the most common errors you’ll encounter when working with the Python strptime() function is a ValueError . This error will indicate that the time data does not match the format. Let’s take a look at how and when this error appears:
In the example above, we passed in a format string that didn’t match the formatting of the string. Because of this, Python can’t infer how to read the string into a datetime object.
In order to fix this error, you can fix the format string. In this case, we need to use the following format string to prevent the error: "%Y-%m-%d %H:%M:%S" .
Working with Milliseconds Using Python strptime Milliseconds
In some cases, you might need to work with date and time data that includes milliseconds. This level of precision can be crucial in certain applications, such as high-frequency trading, scientific experiments, or performance analysis. I’ve personally encountered situations where milliseconds played a vital role in understanding the finer details of data. This is especially true when working with IoT devices, that you’ll often encounter when working in particular industries.
Let’s see how to handle milliseconds when using the strptime function with a code example:
In this example, we have a date and time string that includes milliseconds. To handle this, we add the %f format code to our date format string, which represents microseconds. Since the strptime function supports up to microsecond precision, it will automatically adjust the milliseconds value accordingly.
Now you know how to work with milliseconds using the strptime function, allowing you to handle even more precise date and time data in your projects.
Frequently Asked Questions
To convert a string to a datetime in Python, you can use the strptime function from the datetime module. First, import the datetime module, then call the strptime function with the date string and the corresponding format string as arguments. The format string should match the format of the date string.
To convert a string in the format “yyyy mm dd” to a datetime object in Python, use the strptime function from the datetime module. First, import the datetime module, then call the strptime function with the date string and the format string “%Y %m %d” as arguments. This will return a datetime object representing the given date string.
Yes, you can use the strptime function to convert strings with timezone information. To do this, include the appropriate format codes in your format string, such as %Z for timezone abbreviation (such as EST) or %z for timezone offset (such as -0500). The strptime function will then convert the date and time string, including the timezone information, into a datetime object.
To handle milliseconds when using the strptime function, include the %f format code in your format string. The %f format code represents microseconds, but since the strptime function supports up to microsecond precision, it will automatically adjust the milliseconds value accordingly when converting the date and time string.
Additional Resources
To learn more about related topics, check out the tutorials below:
- Get the Current Date and Time in Python
- Pandas date_range: How to Create a Date Range in Pandas
- Pandas Datetime to Date Parts (Month, Year, etc.)
We’ve covered a lot of ground in this tutorial, and I hope you now feel more confident in using the Python strptime function to convert strings to datetime objects. We started by understanding the basics of the strptime function and its syntax.
We then explored various examples demonstrating how to convert strings with different date and time formats, including handling timezones and milliseconds. We also covered off how to prevent the ValueError that may come up when working with the strptime function.
As you move forward in your Python journey, I encourage you to keep practicing and experimenting with the strptime function. Remember, mastering this function will not only help you convert strings to datetime objects efficiently but also ensure that your data analysis and manipulation tasks are accurate and reliable. Keep up the great work, and happy coding!
To learn more about the Python strptime function, check out the official documentation .
Nik Piepenbreier
Nik is the author of datagy.io and has over a decade of experience working with data analytics, data science, and Python. He specializes in teaching developers how to use Python for data science using hands-on tutorials. View Author posts
6 thoughts on “Python strptime: Converting Strings to DateTime”
Pingback: DateTime in Pandas and Python • datagy
please correct the mistake, swap %y and %Y
correct stuff is %Y: year without century (e.g., 2021) %y: year with century (e.g., 21)
%y: year without century (e.g., 21) %Y: year with century (e.g., 2021)
Thanks for catching this! I have made the revision.
Thanks for this post, but please check the text again for %Y (with) and %y without 😉
Thanks Pieter! I have fixed the typo – thanks for pointing it out 🙂
Leave a Reply Cancel reply
Your email address will not be published. Required fields are marked *
Save my name, email, and website in this browser for the next time I comment.
How to Convert a String to a DateTime Object in Python
When you get dates from raw data, they're typically in the form of string objects. But in this form, you can't access the date's properties like the year, month, and so on.
The solution to this problem is to parse (or convert) the string object into a datetime object so Python can recognized it as a date. And then you can extract any underlying attributes you want to get from it.
This tutorial will teach you how to convert a string to a datetime object in Python. Without further ado, let's get started.
DateTime Format Codes
Before we learn how to convert strings to dates, you should understand the formatting codes of datetime objects in Python.
These prerequisites will be useful whenever you need to convert a string to a date. We will look at some of the most common formatting codes you'll work with anytime you want to convert string to date.
Here are some of the most common:
- %Y — This is used to represent the Year and it ranges from 0001 to 9999
- %m — This is used to represent the month of a year and it ranges from 01 to 12.
- %d — This is used to represent the days of the month and ranges from 01 to 31.
- %H — This is used to represent the hours of the day in a 24-hour format and ranges from 00 to 23.
- %I — This is used to represent the hours of the day in a 12 hour format and ranges from 01 to 12.
- %M — This is used to represents minutes in an hour and ranges from 00 to 59.
- %S — This is used to represents the seconds in a minute and ranges from 00 to 59 as well.
We'll stop here for date format codes, but there are many more in the Python documentation. You can click here to see more.
How to Convert a String to a DateTime Object
Note that the first thing to consider whenever converting a string to date is to make sure that the string is in the right format.
In order to convert a string to a date, it must satisfy the following conditions.
- Firstly, each element in the string must be separated from the others either by a space, letter, or symbol such as / & , % # - and so on.
- The element in the string to be parsed as the year, month, or day must be of the same length as the format code. The element in the string must not exceed the range of the format code. For example the %Y code requires 4 numbers to be passed as the year and its range is 0001 – 9999 (so 09, for example, wouldn't work – you need 2009).
Let's look at some examples of string-to-date conversions. First, we'll convert the string "2019/08/09" to the date.
We need to import the datetime library in Python to be able to achieve this. We can do that by typing the following:
Let's go over the above code again to make sure we understand what's going on.
The format variable declares the format of the date string to be passed to the parser (the function that will help us convert the date). We must be aware of the format ahead of time, that is before we pass it to the parser.
In this case, the string is in the format "2019/08/09".
The first element in the string represents a year, for which the format code is %Y . Then we have a forward slash followed the month, for which the format code is %m . Then we have another forward slash, and finally the day, for which the format code is %d .
As a result, we must include the forward slash symbol in the format variable in the same way that it appears in the string. If everything is done correctly, the format should be "%Y/% m/%d."
The method datetime.strptime is the parser that will help us convert the date_string we passed into it as a date. It requires two parameters: the date string and the format.
When we print it after that, it will look like this.

We can decide to retrieve any attributes we want from it. For example if we wish to get the year only, we can do that by typing date.year and it will print out just the year.
Now that we understand that, let’s go over one more example that is more complex than the above.
Example – how to convert a string to a date
We will convert this string object to a date: "2018-11-15T02:18:49Z" .
Now from the looks of it, we can see that this date string has year, month, day, hours, minutes and seconds. So all we need to do is create the proper format and the symbols in it.
We can see that there is nothing too complex about it. Just follow the format for each part of the date and also pass in any respective symbols or letters you find in the date string.
Do not get distracted by the symbols or letters in the string. If you do everything correctly and print it you should have something like this:

Make sure you don't confuse the format code %m with %M . The small %m is used for months while the big %M is used for minutes.
Conclusion and Learning More
Now we've gotten to the end of this tutorial. You learned how to convert a string into a date format.
Once you learn the format codes, you'll be good to go. Just make sure you adhere to the principles governing which kind of string can be converted.
For instance you have to remember that the string must be separated with something which can either be a space, letter, or symbol. Also, the string range must not be greater or smaller than the range of the format code.
Thank you for reading.
I'm an ardent data scientist who loves breaking and fixing up stuff related to data, and clearly taking care of the data to give me insights as to what it is portraying.
If you read this far, thank the author to show them you care. Say Thanks
Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started
Converting Strings to datetime in Python

- Introduction
Data can be represented in various forms - and a convenient way to represent dates and times are strings . However, to work with these dates and times in an arithmetic fashion (such as calculating time differences, adding or removing time, etc.) - we need to convert them to a datetime object.
One of the most common sources of string-formatted datetimes are REST APIs that return agnostic strings, that we can then convert to other formats.
Additionally - time zones are a common headache when it comes to working with datetime objects, so we'll need to think about that while converting too.
In this guide - we'll take a look at how to convert a string date/time into a datetime object in Python, using the built-in datetime module, but also third-party modules such as dateutil , arrow and Maya, accounting for time zones.
- Converting Strings Using datetime
The datetime module consists of three different object types: date , time , and datetime . The date object holds the date, time holds the time, and datetime holds both date and time!
Running this code would result in:
When no custom formatting is given, the default string format is used, i.e., the format for "2022-12-01 10:27:03.929149" is in ISO 8601 format (YYYY-MM-DDTHH:MM:SS.mmmmmm) . If our input string to create a datetime object is in the same ISO 8601 format or if you know the format you'll be receiving upfront, we can easily parse it to a datetime object:
Running it will print the date, time, and date-time:
Here, we use the strptime() method, which accepts two arguments:
- The string-formatted date
- The format of the first argument
Specifying the format like this makes the parsing much faster since datetime doesn't need to try and interpret the format on its own, which is much more expensive computationally. The return value is of the type datetime .
In our example, "2022-12-01 10:27:03.929149" is the input string and "%Y-%m-%d %H:%M:%S.%f" is the format of our date string. The returned datetime value is stored as date_time_obj .
Since this is a datetime object, we can call the date() and time() methods directly on it. As you can see from the output, it prints the 'date' and 'time' part of the input string!
- Format Tokens
It's worth taking a moment to understand format tokens - the "%Y-%m-%d %H:%M:%S.%f" from before.
Each token represents a different part of the date-time, like day, month, year, day of month or week, etc. The list of supported tokens is extensive enough to enable various formatting. Some of the commonly used ones, that we've also used earlier are:
- %Y : Year (4 digits)
- %d : Day of month
- %H : Hour (24 hour)
- %M : Minutes
- %S : Seconds
- %f : Microseconds
Note: All of these tokens, except the year, are expected to be zero-padded (i.e., August is the 8th month, and is zero-padded to 08 ).
- Using strptime() Format Tokens to Convert String to Different Datetime Format
If the format of a string is known, it can be easily parsed to a datetime object using strptime() . Let's take a look at a non-trivial example that translates from one format to another:
The input string was of one format - "Jul 17 2022 9:20AM". Knowing this format, we mapped the constituent elements to the ISO 8601 format and converted it to a datetime object:
Here's a short list of common string-formatted datetimes and their corresponding formats for strptime() :
You can parse a date-time string of any format - as long as you use the correct string of format tokens for the input you're receiving.
- Convert String to Datetime with Time Zones
Handling date-times becomes more complex while dealing with timezones. All above examples so far are naive to the timezone. These are known as naive datetime objects .
However, the datetime objects contain a field exactly for storing timezone-related data - tzinfo :
The tzinfo field is meant to be a datetime.timezone object, denoting the timezone information. It's None by default, and denotes that the datetime object is timezone-naive. A very common external library for handling timezones is pytz . You can set PyTz objects as the tzinfo field too.
If you don't have it already - install it via:
Using PyTz, we can create an anchor for time-zone aware datetimes, such as UTC:
It's no longer 11AM, but 2AM, because we've set the timezone a few hours back! This changes the timezone of the datetime.
+00:00 is the difference between the displayed time and the UTC time as the global coordination anchor. We've set the time to be in UTC, so the offset is 00:00 . This is a timezone-aware object .
Similarly, we can switch the same datetime's interpretation between time zones. Let's convert a string, such as "2022-06-29 17:08:00" to a datetime and then localize it to the "America/New_York" timezone:
Note: Localization turns a timezone-naive datetime into a timezone-aware datetime, and treats the timezone as the local one. Thus, the datetime stays the same , but given the different timezone, it no longer represents the same point in time unbound from timezones.
We get the same datetime value , offset by -04:00 compared to the UTC time:
17:08 in Tokyo isn't the same point in time as 17:08 in New York. 17:08 in Tokyo is 3:08 in New York.
How to find all of the timezone codes/aliases?
To find all of the available timezones, inspect the all_timezones field, which is a list of all of the available timezones:
Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!
- Change Datetime's Timezone
We can convert the timezone of a timezone-aware datetime object from one region to another, instead of localizing a timezone-naive datetime through the lens of some timezone.
This is different from localization, as localization represents a different point in time, but converting the timezone of an object represents the same point in time, through a different lens:
First, we created one datetime object with the current time and set it as the "America/New_York" timezone. Then using the astimezone() method, we have converted this datetime to "Europe/London" timezone. Both datetime s will print different values, using UTC offset as a reference link between them:
2:24 the next day in London is the same point in time as 21:24 the previous day in New York as London is 5h ahead.
As expected, the date-times are different since they're about 5 hours apart.
- Convert String to Datetime Using Third Party Libraries
Python's datetime module can convert all different types of strings to a datetime object. But the main problem is that in order to do this you need to create the appropriate formatting code string that strptime() can understand. Creating this string takes time and it makes the code harder to read.
Instead, we can use other third-party libraries to make it easier.
In some cases these third-party libraries also have better built-in support for manipulating and comparing date-times, and some even have time zones built-in, so you don't need to include an extra PyTz package.
Let's take a look at a few of these libraries in the following sections.
- Convert String to Datetime with dateutil
The dateutil module is an extension to the datetime module. One advantage is that we don't need to pass any parsing code to parse a string!
To automatically convert a string to datetime without a format token using Python's dateutil :
This parse function will parse the string automatically! You don't have to include any format string. Let's try to parse different types of strings using dateutil :
You can see that almost any type of string can be parsed easily using the dateutil module.
While this is convenient, recall from earlier that having to predict the format makes the code much slower, so if your code requires high performance then this might not be the right approach for your application.
- Convert String to Datetime with Maya
Maya also makes it very easy to parse a string and change time zones. To easily convert a string with Python's Maya:
For converting the time to a different timezone:
Now isn't that easy to use? Let's try out maya with the same set of strings we have used with dateutil :
As you can see, all of the date formats were successfully parsed!
If we don't provide the timezone info then, it automatically converts it to UTC. So, it is important to note that we must provide the to_timezone and naive parameters if the time is not in UTC.
- Convert String to Datetime with Arrow
Arrow is another library for dealing with datetime in Python. And like before with maya , it also figures out the datetime format automatically. Once interpreted, it returns a Python datetime object from the arrow object.
To easily convert a string to datetime using Python's arrow :
And here is how you can use arrow to convert timezones using the to() method:
As you can see the date-time string is converted to the "America/New_York" region.
Now, let's again use the same set of strings we have used above:
This code will fail for the date-time strings that have been commented out, which is over half of our examples. The output for other strings will be:
In order to correctly parse the date-time strings that are commented out, you'll need to pass the corresponding format tokens to give the library clues as to how to parse it.
In this article we have shown different ways to parse a string to a datetime object in Python. You can either opt for the default Python datetime library or any of the third-party libraries mentioned in this article, among many others.
The main problem with the default datetime package is that we need to specify the parsing code manually for almost all date-time string formats. So, if your string format changes in the future, you will likely have to change your code as well. But many third-party libraries, like the ones mentioned here, handle it automatically.
One more problem we face is dealing with timezones. The best way to handle them is always to store the time in your database as UTC format and then convert it to the user's local timezone when needed.
These libraries are not only good for parsing strings, but they can be used for a lot of different types of date-time related operations. I'd encourage you to go through the documents to learn the functionalities in detail.
You might also like...
- Parse Datetime Strings with parsedatetime in Python
- Comparing Datetime with Delorean in Python - With and Without Timezones
- Python: Get Number of Days Between Dates
- Python Docstrings
- The Best Machine Learning Libraries in Python
Improve your dev skills!
Get tutorials, guides, and dev jobs in your inbox.
No spam ever. Unsubscribe at any time. Read our Privacy Policy.
Programmer, blogger, and open source enthusiast. Love to paint and to learn new technologies....
In this article

Building Your First Convolutional Neural Network With Keras
Most resources start with pristine datasets, start at importing and finish at validation. There's much more to know. Why was a class predicted? Where was...

Data Visualization in Python with Matplotlib and Pandas
Data Visualization in Python with Matplotlib and Pandas is a course designed to take absolute beginners to Pandas and Matplotlib, with basic Python knowledge, and...
© 2013- 2023 Stack Abuse. All rights reserved.
Convert String to Datetime in Python
Python doesn't have the date as built-in data type. However, the datetime module in the standard library defines date , time , and datetime classes using which date and time related processing can be done. Objects of these classes are created by providing integer arguments as following:
Hence, we should be able to parse string representation of date/time and obtain arguments for the above constructors. For example, the default string representation of the date is 'YYYY-MM-DD' , for time 'HH:MM:SS' and 'YYYY-MM-DD HH:MM:SS' is for the datetime.
For example, '2020-10-16 12:35:20' is a string representing date and time. We can manually separate date and time attributes and construct the datetime object as follows:
In the above datetime string, the first 10 characters have a year, month and day values separated by '-' and the remaining 8 characters have an hour, min and sec values separated by ':'. You can now unpack the above tuple for the datetime constructor by importing the datetime module, as shown below.
However, the string representation of date and time may vary as per the user's choice. For example, one may use DD-MM-YY format, or someone may want to show month by name, such as 16-Oct-2020 .
This is where the strptime() method of the datetime class proves useful.
The first parameter is the string representation, and the second uses predefined codes to parse date and time values from a string. For example, a date string '2020-10-16' is parsed by this function if the format given is '%Y-%m-%d' . Here, %Y uses the first four characters as four digit representation of a year, the middle two characters as a month and the last two for a date. The module defines the following unique codes for formatting datetime string according to their predefined meaning.
Let's use the strptime() method to convert a given string to a datetime object, as shown below:
If the date string is changed to 'DD-MM-YY' , the format has to be set to %d-%m-%Y .
As a final example, let us set date string as '16-Oct-20'
Note that time parameters appear as 0 as they are not included in the string.
- Remove duplicate items from list in Python
- Remove items from a list in Python
- How to sort dictionary by value in Python?
- Convert User Input to a Number
- How to count the occurrences of a list item?
- How to flatten list in Python?
- How to merge dictionaries in Python?
- Compare strings in Python

Malhar Lathkar is an independent software professional having 30+ years of experience in various technologies such as Python, Java, Android, PHP, and Databases. He is an author of Python Data Persistence: With SQL and NOSQL Databases
- Entrepreneur
- Productivity
- Python »
- 3.11.5 Documentation »
- The Python Standard Library »
- Data Types »
- datetime — Basic date and time types
- Theme Auto Light Dark |
datetime — Basic date and time types ¶
Source code: Lib/datetime.py
The datetime module supplies classes for manipulating dates and times.
While date and time arithmetic is supported, the focus of the implementation is on efficient attribute extraction for output formatting and manipulation.
Skip to the format codes .
General calendar related functions.
Time access and conversions.
Concrete time zones representing the IANA time zone database.
Third-party library with expanded time zone and parsing support.
Third-party library that introduces distinct static types to e.g. allow static type checkers to differentiate between naive and aware datetimes.
Aware and Naive Objects ¶
Date and time objects may be categorized as “aware” or “naive” depending on whether or not they include timezone information.
With sufficient knowledge of applicable algorithmic and political time adjustments, such as time zone and daylight saving time information, an aware object can locate itself relative to other aware objects. An aware object represents a specific moment in time that is not open to interpretation. 1
A naive object does not contain enough information to unambiguously locate itself relative to other date/time objects. Whether a naive object represents Coordinated Universal Time (UTC), local time, or time in some other timezone is purely up to the program, just like it is up to the program whether a particular number represents metres, miles, or mass. Naive objects are easy to understand and to work with, at the cost of ignoring some aspects of reality.
For applications requiring aware objects, datetime and time objects have an optional time zone information attribute, tzinfo , that can be set to an instance of a subclass of the abstract tzinfo class. These tzinfo objects capture information about the offset from UTC time, the time zone name, and whether daylight saving time is in effect.
Only one concrete tzinfo class, the timezone class, is supplied by the datetime module. The timezone class can represent simple timezones with fixed offsets from UTC, such as UTC itself or North American EST and EDT timezones. Supporting timezones at deeper levels of detail is up to the application. The rules for time adjustment across the world are more political than rational, change frequently, and there is no standard suitable for every application aside from UTC.
Constants ¶
The datetime module exports the following constants:
The smallest year number allowed in a date or datetime object. MINYEAR is 1 .
The largest year number allowed in a date or datetime object. MAXYEAR is 9999 .
Alias for the UTC timezone singleton datetime.timezone.utc .
New in version 3.11.
Available Types ¶
An idealized naive date, assuming the current Gregorian calendar always was, and always will be, in effect. Attributes: year , month , and day .
An idealized time, independent of any particular day, assuming that every day has exactly 24*60*60 seconds. (There is no notion of “leap seconds” here.) Attributes: hour , minute , second , microsecond , and tzinfo .
A combination of a date and a time. Attributes: year , month , day , hour , minute , second , microsecond , and tzinfo .
A duration expressing the difference between two date , time , or datetime instances to microsecond resolution.
An abstract base class for time zone information objects. These are used by the datetime and time classes to provide a customizable notion of time adjustment (for example, to account for time zone and/or daylight saving time).
A class that implements the tzinfo abstract base class as a fixed offset from the UTC.
New in version 3.2.
Objects of these types are immutable.
Subclass relationships:
Common Properties ¶
The date , datetime , time , and timezone types share these common features:
Objects of these types are hashable , meaning that they can be used as dictionary keys.
Objects of these types support efficient pickling via the pickle module.
Determining if an Object is Aware or Naive ¶
Objects of the date type are always naive.
An object of type time or datetime may be aware or naive.
A datetime object d is aware if both of the following hold:
d.tzinfo is not None
d.tzinfo.utcoffset(d) does not return None
Otherwise, d is naive.
A time object t is aware if both of the following hold:
t.tzinfo is not None
t.tzinfo.utcoffset(None) does not return None .
Otherwise, t is naive.
The distinction between aware and naive doesn’t apply to timedelta objects.
timedelta Objects ¶
A timedelta object represents a duration, the difference between two dates or times.
All arguments are optional and default to 0 . Arguments may be integers or floats, and may be positive or negative.
Only days , seconds and microseconds are stored internally. Arguments are converted to those units:
A millisecond is converted to 1000 microseconds.
A minute is converted to 60 seconds.
An hour is converted to 3600 seconds.
A week is converted to 7 days.
and days, seconds and microseconds are then normalized so that the representation is unique, with
0 <= microseconds < 1000000
0 <= seconds < 3600*24 (the number of seconds in one day)
-999999999 <= days <= 999999999
The following example illustrates how any arguments besides days , seconds and microseconds are “merged” and normalized into those three resulting attributes:
If any argument is a float and there are fractional microseconds, the fractional microseconds left over from all arguments are combined and their sum is rounded to the nearest microsecond using round-half-to-even tiebreaker. If no argument is a float, the conversion and normalization processes are exact (no information is lost).
If the normalized value of days lies outside the indicated range, OverflowError is raised.
Note that normalization of negative values may be surprising at first. For example:
Class attributes:
The most negative timedelta object, timedelta(-999999999) .
The most positive timedelta object, timedelta(days=999999999, hours=23, minutes=59, seconds=59, microseconds=999999) .
The smallest possible difference between non-equal timedelta objects, timedelta(microseconds=1) .
Note that, because of normalization, timedelta.max > -timedelta.min . -timedelta.max is not representable as a timedelta object.
Instance attributes (read-only):
Supported operations:
This is exact but may overflow.
This is exact and cannot overflow.
Division by 0 raises ZeroDivisionError .
- timedelta.max is not representable as a timedelta object.
String representations of timedelta objects are normalized similarly to their internal representation. This leads to somewhat unusual results for negative timedeltas. For example:
The expression t2 - t3 will always be equal to the expression t2 + (-t3) except when t3 is equal to timedelta.max ; in that case the former will produce a result while the latter will overflow.
In addition to the operations listed above, timedelta objects support certain additions and subtractions with date and datetime objects (see below).
Changed in version 3.2: Floor division and true division of a timedelta object by another timedelta object are now supported, as are remainder operations and the divmod() function. True division and multiplication of a timedelta object by a float object are now supported.
Comparisons of timedelta objects are supported, with some caveats.
The comparisons == or != always return a bool , no matter the type of the compared object:
For all other comparisons (such as < and > ), when a timedelta object is compared to an object of a different type, TypeError is raised:
In Boolean contexts, a timedelta object is considered to be true if and only if it isn’t equal to timedelta(0) .
Instance methods:
Return the total number of seconds contained in the duration. Equivalent to td / timedelta(seconds=1) . For interval units other than seconds, use the division form directly (e.g. td / timedelta(microseconds=1) ).
Note that for very large time intervals (greater than 270 years on most platforms) this method will lose microsecond accuracy.
Examples of usage: timedelta ¶
An additional example of normalization:
Examples of timedelta arithmetic:
date Objects ¶
A date object represents a date (year, month and day) in an idealized calendar, the current Gregorian calendar indefinitely extended in both directions.
January 1 of year 1 is called day number 1, January 2 of year 1 is called day number 2, and so on. 2
All arguments are required. Arguments must be integers, in the following ranges:
MINYEAR <= year <= MAXYEAR
1 <= month <= 12
1 <= day <= number of days in the given month and year
If an argument outside those ranges is given, ValueError is raised.
Other constructors, all class methods:
Return the current local date.
This is equivalent to date.fromtimestamp(time.time()) .
Return the local date corresponding to the POSIX timestamp, such as is returned by time.time() .
This may raise OverflowError , if the timestamp is out of the range of values supported by the platform C localtime() function, and OSError on localtime() failure. It’s common for this to be restricted to years from 1970 through 2038. Note that on non-POSIX systems that include leap seconds in their notion of a timestamp, leap seconds are ignored by fromtimestamp() .
Changed in version 3.3: Raise OverflowError instead of ValueError if the timestamp is out of the range of values supported by the platform C localtime() function. Raise OSError instead of ValueError on localtime() failure.
Return the date corresponding to the proleptic Gregorian ordinal, where January 1 of year 1 has ordinal 1.
ValueError is raised unless 1 <= ordinal <= date.max.toordinal() . For any date d , date.fromordinal(d.toordinal()) == d .
Return a date corresponding to a date_string given in any valid ISO 8601 format, except ordinal dates (e.g. YYYY-DDD ):
New in version 3.7.
Changed in version 3.11: Previously, this method only supported the format YYYY-MM-DD .
Return a date corresponding to the ISO calendar date specified by year, week and day. This is the inverse of the function date.isocalendar() .
New in version 3.8.
The earliest representable date, date(MINYEAR, 1, 1) .
The latest representable date, date(MAXYEAR, 12, 31) .
The smallest possible difference between non-equal date objects, timedelta(days=1) .
Between MINYEAR and MAXYEAR inclusive.
Between 1 and 12 inclusive.
Between 1 and the number of days in the given month of the given year.
date2 is moved forward in time if timedelta.days > 0 , or backward if timedelta.days < 0 . Afterward date2 - date1 == timedelta.days . timedelta.seconds and timedelta.microseconds are ignored. OverflowError is raised if date2.year would be smaller than MINYEAR or larger than MAXYEAR .
timedelta.seconds and timedelta.microseconds are ignored.
This is exact, and cannot overflow. timedelta.seconds and timedelta.microseconds are 0, and date2 + timedelta == date1 after.
In other words, date1 < date2 if and only if date1.toordinal() < date2.toordinal() . Date comparison raises TypeError if the other comparand isn’t also a date object. However, NotImplemented is returned instead if the other comparand has a timetuple() attribute. This hook gives other kinds of date objects a chance at implementing mixed-type comparison. If not, when a date object is compared to an object of a different type, TypeError is raised unless the comparison is == or != . The latter cases return False or True , respectively.
In Boolean contexts, all date objects are considered to be true.
Return a date with the same value, except for those parameters given new values by whichever keyword arguments are specified.
Return a time.struct_time such as returned by time.localtime() .
The hours, minutes and seconds are 0, and the DST flag is -1.
d.timetuple() is equivalent to:
where yday = d.toordinal() - date(d.year, 1, 1).toordinal() + 1 is the day number within the current year starting with 1 for January 1st.
Return the proleptic Gregorian ordinal of the date, where January 1 of year 1 has ordinal 1. For any date object d , date.fromordinal(d.toordinal()) == d .
Return the day of the week as an integer, where Monday is 0 and Sunday is 6. For example, date(2002, 12, 4).weekday() == 2 , a Wednesday. See also isoweekday() .
Return the day of the week as an integer, where Monday is 1 and Sunday is 7. For example, date(2002, 12, 4).isoweekday() == 3 , a Wednesday. See also weekday() , isocalendar() .
Return a named tuple object with three components: year , week and weekday .
The ISO calendar is a widely used variant of the Gregorian calendar. 3
The ISO year consists of 52 or 53 full weeks, and where a week starts on a Monday and ends on a Sunday. The first week of an ISO year is the first (Gregorian) calendar week of a year containing a Thursday. This is called week number 1, and the ISO year of that Thursday is the same as its Gregorian year.
For example, 2004 begins on a Thursday, so the first week of ISO year 2004 begins on Monday, 29 Dec 2003 and ends on Sunday, 4 Jan 2004:
Changed in version 3.9: Result changed from a tuple to a named tuple .
Return a string representing the date in ISO 8601 format, YYYY-MM-DD :
For a date d , str(d) is equivalent to d.isoformat() .
Return a string representing the date:
d.ctime() is equivalent to:
on platforms where the native C ctime() function (which time.ctime() invokes, but which date.ctime() does not invoke) conforms to the C standard.
Return a string representing the date, controlled by an explicit format string. Format codes referring to hours, minutes or seconds will see 0 values. See also strftime() and strptime() Behavior and date.isoformat() .
Same as date.strftime() . This makes it possible to specify a format string for a date object in formatted string literals and when using str.format() . See also strftime() and strptime() Behavior and date.isoformat() .
Examples of Usage: date ¶
Example of counting days to an event:
More examples of working with date :
datetime Objects ¶
A datetime object is a single object containing all the information from a date object and a time object.
Like a date object, datetime assumes the current Gregorian calendar extended in both directions; like a time object, datetime assumes there are exactly 3600*24 seconds in every day.
Constructor:
The year , month and day arguments are required. tzinfo may be None , or an instance of a tzinfo subclass. The remaining arguments must be integers in the following ranges:
MINYEAR <= year <= MAXYEAR ,
1 <= month <= 12 ,
1 <= day <= number of days in the given month and year ,
0 <= hour < 24 ,
0 <= minute < 60 ,
0 <= second < 60 ,
0 <= microsecond < 1000000 ,
fold in [0, 1] .
New in version 3.6: Added the fold argument.
Return the current local datetime, with tzinfo None .
Equivalent to:
See also now() , fromtimestamp() .
This method is functionally equivalent to now() , but without a tz parameter.
Return the current local date and time.
If optional argument tz is None or not specified, this is like today() , but, if possible, supplies more precision than can be gotten from going through a time.time() timestamp (for example, this may be possible on platforms supplying the C gettimeofday() function).
If tz is not None , it must be an instance of a tzinfo subclass, and the current date and time are converted to tz ’s time zone.
This function is preferred over today() and utcnow() .
Return the current UTC date and time, with tzinfo None .
This is like now() , but returns the current UTC date and time, as a naive datetime object. An aware current UTC datetime can be obtained by calling datetime.now(timezone.utc) . See also now() .
Because naive datetime objects are treated by many datetime methods as local times, it is preferred to use aware datetimes to represent times in UTC. As such, the recommended way to create an object representing the current time in UTC is by calling datetime.now(timezone.utc) .
Return the local date and time corresponding to the POSIX timestamp, such as is returned by time.time() . If optional argument tz is None or not specified, the timestamp is converted to the platform’s local date and time, and the returned datetime object is naive.
If tz is not None , it must be an instance of a tzinfo subclass, and the timestamp is converted to tz ’s time zone.
fromtimestamp() may raise OverflowError , if the timestamp is out of the range of values supported by the platform C localtime() or gmtime() functions, and OSError on localtime() or gmtime() failure. It’s common for this to be restricted to years in 1970 through 2038. Note that on non-POSIX systems that include leap seconds in their notion of a timestamp, leap seconds are ignored by fromtimestamp() , and then it’s possible to have two timestamps differing by a second that yield identical datetime objects. This method is preferred over utcfromtimestamp() .
Changed in version 3.3: Raise OverflowError instead of ValueError if the timestamp is out of the range of values supported by the platform C localtime() or gmtime() functions. Raise OSError instead of ValueError on localtime() or gmtime() failure.
Changed in version 3.6: fromtimestamp() may return instances with fold set to 1.
Return the UTC datetime corresponding to the POSIX timestamp, with tzinfo None . (The resulting object is naive.)
This may raise OverflowError , if the timestamp is out of the range of values supported by the platform C gmtime() function, and OSError on gmtime() failure. It’s common for this to be restricted to years in 1970 through 2038.
To get an aware datetime object, call fromtimestamp() :
On the POSIX compliant platforms, it is equivalent to the following expression:
except the latter formula always supports the full years range: between MINYEAR and MAXYEAR inclusive.
Because naive datetime objects are treated by many datetime methods as local times, it is preferred to use aware datetimes to represent times in UTC. As such, the recommended way to create an object representing a specific timestamp in UTC is by calling datetime.fromtimestamp(timestamp, tz=timezone.utc) .
Changed in version 3.3: Raise OverflowError instead of ValueError if the timestamp is out of the range of values supported by the platform C gmtime() function. Raise OSError instead of ValueError on gmtime() failure.
Return the datetime corresponding to the proleptic Gregorian ordinal, where January 1 of year 1 has ordinal 1. ValueError is raised unless 1 <= ordinal <= datetime.max.toordinal() . The hour, minute, second and microsecond of the result are all 0, and tzinfo is None .
Return a new datetime object whose date components are equal to the given date object’s, and whose time components are equal to the given time object’s. If the tzinfo argument is provided, its value is used to set the tzinfo attribute of the result, otherwise the tzinfo attribute of the time argument is used.
For any datetime object d , d == datetime.combine(d.date(), d.time(), d.tzinfo) . If date is a datetime object, its time components and tzinfo attributes are ignored.
Changed in version 3.6: Added the tzinfo argument.
Return a datetime corresponding to a date_string in any valid ISO 8601 format, with the following exceptions:
Time zone offsets may have fractional seconds.
The T separator may be replaced by any single unicode character.
Ordinal dates are not currently supported.
Fractional hours and minutes are not supported.
Changed in version 3.11: Previously, this method only supported formats that could be emitted by date.isoformat() or datetime.isoformat() .
Return a datetime corresponding to the ISO calendar date specified by year, week and day. The non-date components of the datetime are populated with their normal default values. This is the inverse of the function datetime.isocalendar() .
Return a datetime corresponding to date_string , parsed according to format .
If format does not contain microseconds or timezone information, this is equivalent to:
ValueError is raised if the date_string and format can’t be parsed by time.strptime() or if it returns a value which isn’t a time tuple. See also strftime() and strptime() Behavior and datetime.fromisoformat() .
The earliest representable datetime , datetime(MINYEAR, 1, 1, tzinfo=None) .
The latest representable datetime , datetime(MAXYEAR, 12, 31, 23, 59, 59, 999999, tzinfo=None) .
The smallest possible difference between non-equal datetime objects, timedelta(microseconds=1) .
In range(24) .
In range(60) .
In range(1000000) .
The object passed as the tzinfo argument to the datetime constructor, or None if none was passed.
In [0, 1] . Used to disambiguate wall times during a repeated interval. (A repeated interval occurs when clocks are rolled back at the end of daylight saving time or when the UTC offset for the current zone is decreased for political reasons.) The value 0 (1) represents the earlier (later) of the two moments with the same wall time representation.
New in version 3.6.
datetime2 is a duration of timedelta removed from datetime1, moving forward in time if timedelta.days > 0, or backward if timedelta.days < 0. The result has the same tzinfo attribute as the input datetime, and datetime2 - datetime1 == timedelta after. OverflowError is raised if datetime2.year would be smaller than MINYEAR or larger than MAXYEAR . Note that no time zone adjustments are done even if the input is an aware object.
Computes the datetime2 such that datetime2 + timedelta == datetime1. As for addition, the result has the same tzinfo attribute as the input datetime, and no time zone adjustments are done even if the input is aware.
Subtraction of a datetime from a datetime is defined only if both operands are naive, or if both are aware. If one is aware and the other is naive, TypeError is raised.
If both are naive, or both are aware and have the same tzinfo attribute, the tzinfo attributes are ignored, and the result is a timedelta object t such that datetime2 + t == datetime1 . No time zone adjustments are done in this case.
If both are aware and have different tzinfo attributes, a-b acts as if a and b were first converted to naive UTC datetimes first. The result is (a.replace(tzinfo=None) - a.utcoffset()) - (b.replace(tzinfo=None) - b.utcoffset()) except that the implementation never overflows.
datetime1 is considered less than datetime2 when datetime1 precedes datetime2 in time.
If one comparand is naive and the other is aware, TypeError is raised if an order comparison is attempted. For equality comparisons, naive instances are never equal to aware instances.
If both comparands are aware, and have the same tzinfo attribute, the common tzinfo attribute is ignored and the base datetimes are compared. If both comparands are aware and have different tzinfo attributes, the comparands are first adjusted by subtracting their UTC offsets (obtained from self.utcoffset() ).
Changed in version 3.3: Equality comparisons between aware and naive datetime instances don’t raise TypeError .
In order to stop comparison from falling back to the default scheme of comparing object addresses, datetime comparison normally raises TypeError if the other comparand isn’t also a datetime object. However, NotImplemented is returned instead if the other comparand has a timetuple() attribute. This hook gives other kinds of date objects a chance at implementing mixed-type comparison. If not, when a datetime object is compared to an object of a different type, TypeError is raised unless the comparison is == or != . The latter cases return False or True , respectively.
Return date object with same year, month and day.
Return time object with same hour, minute, second, microsecond and fold. tzinfo is None . See also method timetz() .
Changed in version 3.6: The fold value is copied to the returned time object.
Return time object with same hour, minute, second, microsecond, fold, and tzinfo attributes. See also method time() .
Return a datetime with the same attributes, except for those attributes given new values by whichever keyword arguments are specified. Note that tzinfo=None can be specified to create a naive datetime from an aware datetime with no conversion of date and time data.
Return a datetime object with new tzinfo attribute tz , adjusting the date and time data so the result is the same UTC time as self , but in tz ’s local time.
If provided, tz must be an instance of a tzinfo subclass, and its utcoffset() and dst() methods must not return None . If self is naive, it is presumed to represent time in the system timezone.
If called without arguments (or with tz=None ) the system local timezone is assumed for the target timezone. The .tzinfo attribute of the converted datetime instance will be set to an instance of timezone with the zone name and offset obtained from the OS.
If self.tzinfo is tz , self.astimezone(tz) is equal to self : no adjustment of date or time data is performed. Else the result is local time in the timezone tz , representing the same UTC time as self : after astz = dt.astimezone(tz) , astz - astz.utcoffset() will have the same date and time data as dt - dt.utcoffset() .
If you merely want to attach a time zone object tz to a datetime dt without adjustment of date and time data, use dt.replace(tzinfo=tz) . If you merely want to remove the time zone object from an aware datetime dt without conversion of date and time data, use dt.replace(tzinfo=None) .
Note that the default tzinfo.fromutc() method can be overridden in a tzinfo subclass to affect the result returned by astimezone() . Ignoring error cases, astimezone() acts like:
Changed in version 3.3: tz now can be omitted.
Changed in version 3.6: The astimezone() method can now be called on naive instances that are presumed to represent system local time.
If tzinfo is None , returns None , else returns self.tzinfo.utcoffset(self) , and raises an exception if the latter doesn’t return None or a timedelta object with magnitude less than one day.
Changed in version 3.7: The UTC offset is not restricted to a whole number of minutes.
If tzinfo is None , returns None , else returns self.tzinfo.dst(self) , and raises an exception if the latter doesn’t return None or a timedelta object with magnitude less than one day.
Changed in version 3.7: The DST offset is not restricted to a whole number of minutes.
If tzinfo is None , returns None , else returns self.tzinfo.tzname(self) , raises an exception if the latter doesn’t return None or a string object,
where yday = d.toordinal() - date(d.year, 1, 1).toordinal() + 1 is the day number within the current year starting with 1 for January 1st. The tm_isdst flag of the result is set according to the dst() method: tzinfo is None or dst() returns None , tm_isdst is set to -1 ; else if dst() returns a non-zero value, tm_isdst is set to 1 ; else tm_isdst is set to 0 .
If datetime instance d is naive, this is the same as d.timetuple() except that tm_isdst is forced to 0 regardless of what d.dst() returns. DST is never in effect for a UTC time.
If d is aware, d is normalized to UTC time, by subtracting d.utcoffset() , and a time.struct_time for the normalized time is returned. tm_isdst is forced to 0. Note that an OverflowError may be raised if d .year was MINYEAR or MAXYEAR and UTC adjustment spills over a year boundary.
Because naive datetime objects are treated by many datetime methods as local times, it is preferred to use aware datetimes to represent times in UTC; as a result, using datetime.utctimetuple() may give misleading results. If you have a naive datetime representing UTC, use datetime.replace(tzinfo=timezone.utc) to make it aware, at which point you can use datetime.timetuple() .
Return the proleptic Gregorian ordinal of the date. The same as self.date().toordinal() .
Return POSIX timestamp corresponding to the datetime instance. The return value is a float similar to that returned by time.time() .
Naive datetime instances are assumed to represent local time and this method relies on the platform C mktime() function to perform the conversion. Since datetime supports wider range of values than mktime() on many platforms, this method may raise OverflowError for times far in the past or far in the future.
For aware datetime instances, the return value is computed as:
New in version 3.3.
Changed in version 3.6: The timestamp() method uses the fold attribute to disambiguate the times during a repeated interval.
There is no method to obtain the POSIX timestamp directly from a naive datetime instance representing UTC time. If your application uses this convention and your system timezone is not set to UTC, you can obtain the POSIX timestamp by supplying tzinfo=timezone.utc :
or by calculating the timestamp directly:
Return the day of the week as an integer, where Monday is 0 and Sunday is 6. The same as self.date().weekday() . See also isoweekday() .
Return the day of the week as an integer, where Monday is 1 and Sunday is 7. The same as self.date().isoweekday() . See also weekday() , isocalendar() .
Return a named tuple with three components: year , week and weekday . The same as self.date().isocalendar() .
Return a string representing the date and time in ISO 8601 format:
YYYY-MM-DDTHH:MM:SS.ffffff , if microsecond is not 0
YYYY-MM-DDTHH:MM:SS , if microsecond is 0
If utcoffset() does not return None , a string is appended, giving the UTC offset:
YYYY-MM-DDTHH:MM:SS.ffffff+HH:MM[:SS[.ffffff]] , if microsecond is not 0
YYYY-MM-DDTHH:MM:SS+HH:MM[:SS[.ffffff]] , if microsecond is 0
The optional argument sep (default 'T' ) is a one-character separator, placed between the date and time portions of the result. For example:
The optional argument timespec specifies the number of additional components of the time to include (the default is 'auto' ). It can be one of the following:
'auto' : Same as 'seconds' if microsecond is 0, same as 'microseconds' otherwise.
'hours' : Include the hour in the two-digit HH format.
'minutes' : Include hour and minute in HH:MM format.
'seconds' : Include hour , minute , and second in HH:MM:SS format.
'milliseconds' : Include full time, but truncate fractional second part to milliseconds. HH:MM:SS.sss format.
'microseconds' : Include full time in HH:MM:SS.ffffff format.
Excluded time components are truncated, not rounded.
ValueError will be raised on an invalid timespec argument:
New in version 3.6: Added the timespec argument.
For a datetime instance d , str(d) is equivalent to d.isoformat(' ') .
Return a string representing the date and time:
The output string will not include time zone information, regardless of whether the input is aware or naive.
on platforms where the native C ctime() function (which time.ctime() invokes, but which datetime.ctime() does not invoke) conforms to the C standard.
Return a string representing the date and time, controlled by an explicit format string. See also strftime() and strptime() Behavior and datetime.isoformat() .
Same as datetime.strftime() . This makes it possible to specify a format string for a datetime object in formatted string literals and when using str.format() . See also strftime() and strptime() Behavior and datetime.isoformat() .
Examples of Usage: datetime ¶
Examples of working with datetime objects:
The example below defines a tzinfo subclass capturing time zone information for Kabul, Afghanistan, which used +4 UTC until 1945 and then +4:30 UTC thereafter:
Usage of KabulTz from above:
time Objects ¶
A time object represents a (local) time of day, independent of any particular day, and subject to adjustment via a tzinfo object.
All arguments are optional. tzinfo may be None , or an instance of a tzinfo subclass. The remaining arguments must be integers in the following ranges:
If an argument outside those ranges is given, ValueError is raised. All default to 0 except tzinfo , which defaults to None .
The earliest representable time , time(0, 0, 0, 0) .
The latest representable time , time(23, 59, 59, 999999) .
The smallest possible difference between non-equal time objects, timedelta(microseconds=1) , although note that arithmetic on time objects is not supported.
The object passed as the tzinfo argument to the time constructor, or None if none was passed.
time objects support comparison of time to time , where a is considered less than b when a precedes b in time. If one comparand is naive and the other is aware, TypeError is raised if an order comparison is attempted. For equality comparisons, naive instances are never equal to aware instances.
If both comparands are aware, and have the same tzinfo attribute, the common tzinfo attribute is ignored and the base times are compared. If both comparands are aware and have different tzinfo attributes, the comparands are first adjusted by subtracting their UTC offsets (obtained from self.utcoffset() ). In order to stop mixed-type comparisons from falling back to the default comparison by object address, when a time object is compared to an object of a different type, TypeError is raised unless the comparison is == or != . The latter cases return False or True , respectively.
Changed in version 3.3: Equality comparisons between aware and naive time instances don’t raise TypeError .
In Boolean contexts, a time object is always considered to be true.
Changed in version 3.5: Before Python 3.5, a time object was considered to be false if it represented midnight in UTC. This behavior was considered obscure and error-prone and has been removed in Python 3.5. See bpo-13936 for full details.
Other constructor:
Return a time corresponding to a time_string in any valid ISO 8601 format, with the following exceptions:
The leading T , normally required in cases where there may be ambiguity between a date and a time, is not required.
Fractional seconds may have any number of digits (anything beyond 6 will be truncated).
Changed in version 3.11: Previously, this method only supported formats that could be emitted by time.isoformat() .
Return a time with the same value, except for those attributes given new values by whichever keyword arguments are specified. Note that tzinfo=None can be specified to create a naive time from an aware time , without conversion of the time data.
Return a string representing the time in ISO 8601 format, one of:
HH:MM:SS.ffffff , if microsecond is not 0
HH:MM:SS , if microsecond is 0
HH:MM:SS.ffffff+HH:MM[:SS[.ffffff]] , if utcoffset() does not return None
HH:MM:SS+HH:MM[:SS[.ffffff]] , if microsecond is 0 and utcoffset() does not return None
ValueError will be raised on an invalid timespec argument.
For a time t , str(t) is equivalent to t.isoformat() .
Return a string representing the time, controlled by an explicit format string. See also strftime() and strptime() Behavior and time.isoformat() .
Same as time.strftime() . This makes it possible to specify a format string for a time object in formatted string literals and when using str.format() . See also strftime() and strptime() Behavior and time.isoformat() .
If tzinfo is None , returns None , else returns self.tzinfo.utcoffset(None) , and raises an exception if the latter doesn’t return None or a timedelta object with magnitude less than one day.
If tzinfo is None , returns None , else returns self.tzinfo.dst(None) , and raises an exception if the latter doesn’t return None , or a timedelta object with magnitude less than one day.
If tzinfo is None , returns None , else returns self.tzinfo.tzname(None) , or raises an exception if the latter doesn’t return None or a string object.
Examples of Usage: time ¶
Examples of working with a time object:
tzinfo Objects ¶
This is an abstract base class, meaning that this class should not be instantiated directly. Define a subclass of tzinfo to capture information about a particular time zone.
An instance of (a concrete subclass of) tzinfo can be passed to the constructors for datetime and time objects. The latter objects view their attributes as being in local time, and the tzinfo object supports methods revealing offset of local time from UTC, the name of the time zone, and DST offset, all relative to a date or time object passed to them.
You need to derive a concrete subclass, and (at least) supply implementations of the standard tzinfo methods needed by the datetime methods you use. The datetime module provides timezone , a simple concrete subclass of tzinfo which can represent timezones with fixed offset from UTC such as UTC itself or North American EST and EDT.
Special requirement for pickling: A tzinfo subclass must have an __init__() method that can be called with no arguments, otherwise it can be pickled but possibly not unpickled again. This is a technical requirement that may be relaxed in the future.
A concrete subclass of tzinfo may need to implement the following methods. Exactly which methods are needed depends on the uses made of aware datetime objects. If in doubt, simply implement all of them.
Return offset of local time from UTC, as a timedelta object that is positive east of UTC. If local time is west of UTC, this should be negative.
This represents the total offset from UTC; for example, if a tzinfo object represents both time zone and DST adjustments, utcoffset() should return their sum. If the UTC offset isn’t known, return None . Else the value returned must be a timedelta object strictly between -timedelta(hours=24) and timedelta(hours=24) (the magnitude of the offset must be less than one day). Most implementations of utcoffset() will probably look like one of these two:
If utcoffset() does not return None , dst() should not return None either.
The default implementation of utcoffset() raises NotImplementedError .
Return the daylight saving time (DST) adjustment, as a timedelta object or None if DST information isn’t known.
Return timedelta(0) if DST is not in effect. If DST is in effect, return the offset as a timedelta object (see utcoffset() for details). Note that DST offset, if applicable, has already been added to the UTC offset returned by utcoffset() , so there’s no need to consult dst() unless you’re interested in obtaining DST info separately. For example, datetime.timetuple() calls its tzinfo attribute’s dst() method to determine how the tm_isdst flag should be set, and tzinfo.fromutc() calls dst() to account for DST changes when crossing time zones.
An instance tz of a tzinfo subclass that models both standard and daylight times must be consistent in this sense:
tz.utcoffset(dt) - tz.dst(dt)
must return the same result for every datetime dt with dt.tzinfo == tz For sane tzinfo subclasses, this expression yields the time zone’s “standard offset”, which should not depend on the date or the time, but only on geographic location. The implementation of datetime.astimezone() relies on this, but cannot detect violations; it’s the programmer’s responsibility to ensure it. If a tzinfo subclass cannot guarantee this, it may be able to override the default implementation of tzinfo.fromutc() to work correctly with astimezone() regardless.
Most implementations of dst() will probably look like one of these two:
The default implementation of dst() raises NotImplementedError .
Return the time zone name corresponding to the datetime object dt , as a string. Nothing about string names is defined by the datetime module, and there’s no requirement that it mean anything in particular. For example, “GMT”, “UTC”, “-500”, “-5:00”, “EDT”, “US/Eastern”, “America/New York” are all valid replies. Return None if a string name isn’t known. Note that this is a method rather than a fixed string primarily because some tzinfo subclasses will wish to return different names depending on the specific value of dt passed, especially if the tzinfo class is accounting for daylight time.
The default implementation of tzname() raises NotImplementedError .
These methods are called by a datetime or time object, in response to their methods of the same names. A datetime object passes itself as the argument, and a time object passes None as the argument. A tzinfo subclass’s methods should therefore be prepared to accept a dt argument of None , or of class datetime .
When None is passed, it’s up to the class designer to decide the best response. For example, returning None is appropriate if the class wishes to say that time objects don’t participate in the tzinfo protocols. It may be more useful for utcoffset(None) to return the standard UTC offset, as there is no other convention for discovering the standard offset.
When a datetime object is passed in response to a datetime method, dt.tzinfo is the same object as self . tzinfo methods can rely on this, unless user code calls tzinfo methods directly. The intent is that the tzinfo methods interpret dt as being in local time, and not need worry about objects in other timezones.
There is one more tzinfo method that a subclass may wish to override:
This is called from the default datetime.astimezone() implementation. When called from that, dt.tzinfo is self , and dt ’s date and time data are to be viewed as expressing a UTC time. The purpose of fromutc() is to adjust the date and time data, returning an equivalent datetime in self ’s local time.
Most tzinfo subclasses should be able to inherit the default fromutc() implementation without problems. It’s strong enough to handle fixed-offset time zones, and time zones accounting for both standard and daylight time, and the latter even if the DST transition times differ in different years. An example of a time zone the default fromutc() implementation may not handle correctly in all cases is one where the standard offset (from UTC) depends on the specific date and time passed, which can happen for political reasons. The default implementations of astimezone() and fromutc() may not produce the result you want if the result is one of the hours straddling the moment the standard offset changes.
Skipping code for error cases, the default fromutc() implementation acts like:
In the following tzinfo_examples.py file there are some examples of tzinfo classes:
Note that there are unavoidable subtleties twice per year in a tzinfo subclass accounting for both standard and daylight time, at the DST transition points. For concreteness, consider US Eastern (UTC -0500), where EDT begins the minute after 1:59 (EST) on the second Sunday in March, and ends the minute after 1:59 (EDT) on the first Sunday in November:
When DST starts (the “start” line), the local wall clock leaps from 1:59 to 3:00. A wall time of the form 2:MM doesn’t really make sense on that day, so astimezone(Eastern) won’t deliver a result with hour == 2 on the day DST begins. For example, at the Spring forward transition of 2016, we get:
When DST ends (the “end” line), there’s a potentially worse problem: there’s an hour that can’t be spelled unambiguously in local wall time: the last hour of daylight time. In Eastern, that’s times of the form 5:MM UTC on the day daylight time ends. The local wall clock leaps from 1:59 (daylight time) back to 1:00 (standard time) again. Local times of the form 1:MM are ambiguous. astimezone() mimics the local clock’s behavior by mapping two adjacent UTC hours into the same local hour then. In the Eastern example, UTC times of the form 5:MM and 6:MM both map to 1:MM when converted to Eastern, but earlier times have the fold attribute set to 0 and the later times have it set to 1. For example, at the Fall back transition of 2016, we get:
Note that the datetime instances that differ only by the value of the fold attribute are considered equal in comparisons.
Applications that can’t bear wall-time ambiguities should explicitly check the value of the fold attribute or avoid using hybrid tzinfo subclasses; there are no ambiguities when using timezone , or any other fixed-offset tzinfo subclass (such as a class representing only EST (fixed offset -5 hours), or only EDT (fixed offset -4 hours)).
zoneinfo The datetime module has a basic timezone class (for handling arbitrary fixed offsets from UTC) and its timezone.utc attribute (a UTC timezone instance). zoneinfo brings the IANA timezone database (also known as the Olson database) to Python, and its usage is recommended.
The Time Zone Database (often called tz, tzdata or zoneinfo) contains code and data that represent the history of local time for many representative locations around the globe. It is updated periodically to reflect changes made by political bodies to time zone boundaries, UTC offsets, and daylight-saving rules.
timezone Objects ¶
The timezone class is a subclass of tzinfo , each instance of which represents a timezone defined by a fixed offset from UTC.
Objects of this class cannot be used to represent timezone information in the locations where different offsets are used in different days of the year or where historical changes have been made to civil time.
The offset argument must be specified as a timedelta object representing the difference between the local time and UTC. It must be strictly between -timedelta(hours=24) and timedelta(hours=24) , otherwise ValueError is raised.
The name argument is optional. If specified it must be a string that will be used as the value returned by the datetime.tzname() method.
Return the fixed value specified when the timezone instance is constructed.
The dt argument is ignored. The return value is a timedelta instance equal to the difference between the local time and UTC.
If name is not provided in the constructor, the name returned by tzname(dt) is generated from the value of the offset as follows. If offset is timedelta(0) , the name is “UTC”, otherwise it is a string in the format UTC±HH:MM , where ± is the sign of offset , HH and MM are two digits of offset.hours and offset.minutes respectively.
Changed in version 3.6: Name generated from offset=timedelta(0) is now plain 'UTC' , not 'UTC+00:00' .
Always returns None .
Return dt + offset . The dt argument must be an aware datetime instance, with tzinfo set to self .
The UTC timezone, timezone(timedelta(0)) .
strftime() and strptime() Behavior ¶
date , datetime , and time objects all support a strftime(format) method, to create a string representing the time under the control of an explicit format string.
Conversely, the datetime.strptime() class method creates a datetime object from a string representing a date and time and a corresponding format string.
The table below provides a high-level comparison of strftime() versus strptime() :
strftime() and strptime() Format Codes ¶
These methods accept format codes that can be used to parse and format dates:
The following is a list of all the format codes that the 1989 C standard requires, and these work on all platforms with a standard C implementation.
Several additional directives not required by the C89 standard are included for convenience. These parameters all correspond to ISO 8601 date values.
These may not be available on all platforms when used with the strftime() method. The ISO 8601 year and ISO 8601 week directives are not interchangeable with the year and week number directives above. Calling strptime() with incomplete or ambiguous ISO 8601 directives will raise a ValueError .
The full set of format codes supported varies across platforms, because Python calls the platform C library’s strftime() function, and platform variations are common. To see the full set of format codes supported on your platform, consult the strftime(3) documentation. There are also differences between platforms in handling of unsupported format specifiers.
New in version 3.6: %G , %u and %V were added.
Technical Detail ¶
Broadly speaking, d.strftime(fmt) acts like the time module’s time.strftime(fmt, d.timetuple()) although not all objects support a timetuple() method.
For the datetime.strptime() class method, the default value is 1900-01-01T00:00:00.000 : any components not specified in the format string will be pulled from the default value. 4
Using datetime.strptime(date_string, format) is equivalent to:
except when the format includes sub-second components or timezone offset information, which are supported in datetime.strptime but are discarded by time.strptime .
For time objects, the format codes for year, month, and day should not be used, as time objects have no such values. If they’re used anyway, 1900 is substituted for the year, and 1 for the month and day.
For date objects, the format codes for hours, minutes, seconds, and microseconds should not be used, as date objects have no such values. If they’re used anyway, 0 is substituted for them.
For the same reason, handling of format strings containing Unicode code points that can’t be represented in the charset of the current locale is also platform-dependent. On some platforms such code points are preserved intact in the output, while on others strftime may raise UnicodeError or return an empty string instead.
Because the format depends on the current locale, care should be taken when making assumptions about the output value. Field orderings will vary (for example, “month/day/year” versus “day/month/year”), and the output may contain non-ASCII characters.
The strptime() method can parse years in the full [1, 9999] range, but years < 1000 must be zero-filled to 4-digit width.
Changed in version 3.2: In previous versions, strftime() method was restricted to years >= 1900.
Changed in version 3.3: In version 3.2, strftime() method was restricted to years >= 1000.
When used with the strptime() method, the %p directive only affects the output hour field if the %I directive is used to parse the hour.
Unlike the time module, the datetime module does not support leap seconds.
When used with the strptime() method, the %f directive accepts from one to six digits and zero pads on the right. %f is an extension to the set of format characters in the C standard (but implemented separately in datetime objects, and therefore always available).
For a naive object, the %z and %Z format codes are replaced by empty strings.
For an aware object:
utcoffset() is transformed into a string of the form ±HHMM[SS[.ffffff]] , where HH is a 2-digit string giving the number of UTC offset hours, MM is a 2-digit string giving the number of UTC offset minutes, SS is a 2-digit string giving the number of UTC offset seconds and ffffff is a 6-digit string giving the number of UTC offset microseconds. The ffffff part is omitted when the offset is a whole number of seconds and both the ffffff and the SS part is omitted when the offset is a whole number of minutes. For example, if utcoffset() returns timedelta(hours=-3, minutes=-30) , %z is replaced with the string '-0330' .
Changed in version 3.7: When the %z directive is provided to the strptime() method, the UTC offsets can have a colon as a separator between hours, minutes and seconds. For example, '+01:00:00' will be parsed as an offset of one hour. In addition, providing 'Z' is identical to '+00:00' .
In strftime() , %Z is replaced by an empty string if tzname() returns None ; otherwise %Z is replaced by the returned value, which must be a string.
strptime() only accepts certain values for %Z :
any value in time.tzname for your machine’s locale
the hard-coded values UTC and GMT
So someone living in Japan may have JST , UTC , and GMT as valid values, but probably not EST . It will raise ValueError for invalid values.
Changed in version 3.2: When the %z directive is provided to the strptime() method, an aware datetime object will be produced. The tzinfo of the result will be set to a timezone instance.
When used with the strptime() method, %U and %W are only used in calculations when the day of the week and the calendar year ( %Y ) are specified.
Similar to %U and %W , %V is only used in calculations when the day of the week and the ISO year ( %G ) are specified in a strptime() format string. Also note that %G and %Y are not interchangeable.
When used with the strptime() method, the leading zero is optional for formats %d , %m , %H , %I , %M , %S , %j , %U , %W , and %V . Format %y does require a leading zero.
If, that is, we ignore the effects of Relativity
This matches the definition of the “proleptic Gregorian” calendar in Dershowitz and Reingold’s book Calendrical Calculations , where it’s the base calendar for all computations. See the book for algorithms for converting between proleptic Gregorian ordinals and many other calendar systems.
See R. H. van Gent’s guide to the mathematics of the ISO 8601 calendar for a good explanation.
Passing datetime.strptime('Feb 29', '%b %d') will fail since 1900 is not a leap year.
Table of Contents
- Aware and Naive Objects
- Common Properties
- Determining if an Object is Aware or Naive
- Examples of usage: timedelta
- Examples of Usage: date
- Examples of Usage: datetime
- Examples of Usage: time
- tzinfo Objects
- timezone Objects
- strftime() and strptime() Format Codes
- Technical Detail
Previous topic
zoneinfo — IANA time zone support
- Report a Bug
- Show Source
- [email protected]

What’s New ?
The Top 10 favtutor Features You Might Have Overlooked

- Don’t have an account Yet? Sign Up
Remember me Forgot your password?
- Already have an Account? Sign In
Lost your password? Please enter your email address. You will receive a link to create a new password.
Back to log-in
By Signing up for Favtutor, you agree to our Terms of Service & Privacy Policy.
How to Convert String to DateTime in Python? (with code)
- Mar 10, 2023
- 7 Minutes Read
- By Abrar Ahmed

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":
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":
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:
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":
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
More by favtutor blogs, diagonal traversal of binary tree (with code), vedanti kshirsagar.

Find Largest BST in Binary Tree (with code)

Longest Alternating Subsequence Problem (with Solution)

How to Convert a String to DateTime in Python?
This Python tutorial explains, how to convert a string to datetime in Python . I will also show you, how to convert string to datetime with timezone in Python .
Converting a string to a DateTime object is a common task when you’re dealing with data that involves timestamps. Python makes this relatively straightforward with the help of the datetime module.
Table of Contents
Convert a String to DateTime in Python
Let us see, how to convert a string into datetime in Python.
In this example, I have imported a module called DateTime.
To get the output we will print((datetime.datetime.now())) . You can refer to the below screenshot for the output:

Convert a string to datetime with timezone in Python
In Python, converting a string into a datetime object with a timezone requires using the datetime module. Specifically, you’ll have to work with the datetime class, the timezone class, and the strptime method.
Now, we can see how to convert a string to datetime with timezone in Python.
In this example, I have imported a module called timezone . datetime.now(timezone(‘UTC’)) is used to get the present time with the timezone. The format is assigned as time = “%Y-%m-%d %H:%M:%S%Z%z”. The %z is used to get timezone along with DateTime.
To get the output print(‘UTC :’, time) is used. In the below screenshot, we can see the output.

Convert string to datetime with timezone in Python
Converting a string to a datetime object with a timezone in Python involves parsing the string into a datetime object and then associating it with the desired timezone. To achieve this, you can use the datetime module in Python. Here’s a step-by-step guide:
- First, import the necessary classes from the datetime module. You will need the datetime class itself, along with the timezone and timedelta classes.
- Before converting the string to a datetime object, you need to understand its format. This is important because you will need to inform Python how to interpret the string.
Common formats include:
- ‘%Y-%m-%d’ for “2023-06-18”
- ‘%Y-%m-%d %H:%M:%S’ for “2023-06-18 15:30:20”
- You can use the strptime method from the datetime class to convert the string into a datetime object. strptime stands for “string parse time”, and it requires two arguments: the string and its format.
- If the string you’re parsing includes timezone information, Python will automatically parse this as well. If not, you can associate a timezone manually. To associate a timezone manually, use the replace method to attach a timezone. Here’s how you can do it:
- If the string already includes timezone information, you can parse it directly:
Here is a full code:
This code demonstrates how to convert a string to a datetime object and associate it with timezone information in Python. You can check out the below output:

Convert a string to datetime with milliseconds in Python
Let us see how to convert a string to datetime with milliseconds in Python.
In this example, I have imported a module called DateTime . The dt = datetime.datetime.now() is used to get the present time . Here, %f is used to get time with milliseconds.
To get the output as datetime with milliseconds print(dt) . You can refer to the below screenshot for the output:

Convert a string to datetime iso format in Python
Here, we can see how to convert a string to datetime iso format in Python .
In this example, I have imported a module called datetime and used .isoformat to convert present time into iso format.
To get the output in iso format, here I have used print(dt.isoformat()) . You can see the below screenshot for output:

Convert a string to datetime yyyy-mm-dd in Python
Now we can see, how to convert a string to datetime yyyy-mm-dd in Python.
- In this example, I have imported a module called datetime . And assigned input as “2020-12-21 ” to the variable as dt_string, and the format as format = “%Y-%m-%d”.
- strptime is a string that represents a time according to format.
- dt_object = datetime.datetime.strptime(dt_string, format) In this two arguments are passed one is dt_string and other one is format .
To get the output print(dt_object) is used in this example. You can refer to the below screenshot for the output:

How to convert a string to datetime UTC in Python
Here, we can see how to convert a string to datetime utc format in Python.
- In this example, I have imported modules called pytz and datetime . And assigned the timezone as pytz.timezone (“Asia/Kolkata “).
- Pytz is a library used for timezone calculation and lc.localize() is used to make a naive timezone. A simple datetime object is called a timezone naive, and lc_datetime.astimezone() is a function used to set the time according to the required timezone.
To get the output as time in UTC format print(utc_date_time) , and it will return date and time . You can refer to the below screenshot for the output.

You may like the following Python tutorials:
- Escape Sequence in Python
- Convert Degrees to Radians in Python
- How to Convert bool to int in Python
- Python Generator vs Iterator Performance
This Python tutorial explains, how to convert string to datetime with timezone in Python .

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile .
How to convert STRING to DateTime in Python?
This recipe helps you convert STRING to DateTime in Python Last Updated: 22 Dec 2022
- Recipe Objective
Have you ever tried to work on datetime features in a dataset ? It may look quite complicated to write datetime in its format, we can write date and time in form of strings but how to convert it in DateTime Stamp.
Converting strings to datetime objects in Python has become a common practice for data scientists especially in time series projects. Performing this is often times difficult due to various date formats - different month lengths, timezone variations etc.
To solve this, Python provides a specific data type called "datetime". But in many datasets, the dates might be represented as strings. This recipe demonstrates how to convert date strings to the datetime format.
datetime.strptime is the primary routine for parsing strings into datetimes. datetime.strptime(date_string, format)
Once you have your value in datetime objects, you can then extract specific components of the date such as the month, day, or year, all of which are available as the object's attributes.
So this is the recipe on how we can change string to DateTime in Python. In this we will do this by using three different functions.
Get Closer To Your Dream of Becoming a Data Scientist with 70+ Solved End-to-End ML Projects
Table of Contents
Method 1 - converting string into datetime, method 2 - converting string into datetime, method 3 - converting string into datetime, step 1 - import the library.
from datetime import datetime from dateutil.parser import parse import pandas as pd
We have imported datetime, parse and pandas. These three modules will be required.
We have first defined an object called date_start in which we have stored an string in format %Y-%m-%d. Then we have tried to print it as a DateTime Stamp by using function datetime.strptime. date_start = '2020-01-01' print(datetime.strptime(date_start, '%Y-%m-%d'))
We have created a list of date in the format %m/%d/%y and used parse function on all the values of date_list to convert it in the format of datetime64. date_list = ['2/7/2027', '6/8/2019', '10/25/2020', '6/29/2018', '2/5/2022'] print([parse(x) for x in date_list])
Explore More Data Science and Machine Learning Projects for Practice. Fast-Track Your Career Transition with ProjectPro
We have created a dictionary of values and passed in function pd.DataFrame to change it into a DataFrame with columns date and value. Then we have checked the data type in the dataframe (ie object) and to change it to datetime format, we have used pd.to_datetime function. data = {'date': ['2020-05-01 18:47:05.069722', '2016-01-01 18:47:05.119994', '2014-02-05 18:47:05.178768', '2018-04-02 18:47:05.230071', '2018-04-06 18:47:05.230071', '2019-08-02 18:47:05.280592', '2019-07-01 18:47:05.332662', '2011-03-03 18:47:05.385109', '2024-04-09 18:47:05.436523', '2015-04-04 18:47:05.486877'], 'value': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]} df = pd.DataFrame(data, columns = ['date', 'value']) print(df.dtypes) print(pd.to_datetime(df['date'])) print(pd.to_datetime(df['date']).dtypes) So the final output of all the methods are
Download Materials

What Users are saying..

Savvy Sahai

As a student looking to break into the field of data engineering and data science, one can get really confused as to which path to take. Very few ways to do it are Google, YouTube, etc. I was one of... Read More
Relevant Projects
Machine learning projects, data science projects, python projects for data science, data science projects in r, machine learning projects for beginners, deep learning projects, neural network projects, tensorflow projects, nlp projects, kaggle projects, iot projects, big data projects, hadoop real-time projects examples, spark projects, data analytics projects for students, you might also like, data science tutorial, data scientist salary, how to become a data scientist, data analyst vs data scientist, data scientist resume, data science projects for beginners, machine learning engineer, pandas dataframe, machine learning algorithms, regression analysis, mnist dataset, data science interview questions, python data science interview questions, spark interview questions, hadoop interview questions, data analyst interview questions, machine learning interview questions, aws vs azure, hadoop architecture, spark architecture.

Hands-On Approach to Regression Discontinuity Design Python

Word2Vec and FastText Word Embedding with Gensim in Python

Demand prediction of driver availability using multistep time series analysis

Deploying Machine Learning Models with Flask for Beginners

AWS MLOps Project to Deploy Multiple Linear Regression Model

Tensorflow Transfer Learning Model for Image Classification

Build Multi Class Text Classification Models with RNN and LSTM

MLOps Project on GCP using Kubeflow for Model Deployment

Build Regression (Linear,Ridge,Lasso) Models in NumPy Python

Build a Multi Class Image Classification Model Python using CNN
Subscribe to recipes, sign up to view recipe.

Data to Fish
How to Convert Strings to Datetime in Pandas DataFrame
You may use this template in order to convert strings to datetime in Pandas DataFrame:
Note that the strings must match the format specified. Later, you’ll see several scenarios for different formats.
Steps to Convert Strings to Datetime in Pandas DataFrame
Step 1: collect the data to be converted.
To begin, collect the data that you’d like to convert to datetime.
For example, here is a simple dataset about 3 different dates (with a format of yyyymmdd ), when a store might be opened or closed:
Step 2: Create a DataFrame
Next, create a DataFrame to capture the above data in Python. You can capture the dates as strings by placing quotes around the values under the ‘dates’ column:
Run the code in Python, and you’ll get this DataFrame:
Notice that the ‘dates’ were indeed stored as strings (represented by object ).
Step 3: Convert the Strings to Datetime in the DataFrame
You may then use the template below in order to convert the strings to datetime in Pandas DataFrame:
Recall that for our example, the date format is yyyymmdd .
This date format can be represented as:
Note that the strings data (yyyymmdd) must match the format specified (%Y%m%d). You may refer to the following source for the different formats that you may apply.
For our example, the complete Python code to convert the strings to datetime would be:
You’ll see that the data type for the ‘dates’ column is now datetime:
Note that when applying pd.to_datetime, the default format is yyyymmdd. So in the above particular example, you could remove the format =’%Y%m%d’ from the code. However, in other scenarios, as you’ll see below, you must specify the correct format to match with the strings data.
Converting Additional Formats
Let’s say that the dates are now formatted as ddmmyyyy :
In that case, you’ll need to apply the format below (for reference, check the following table to identify the correct format that you should apply):
Here is the complete Python code:
As before, your strings will now get converted to datetime:
What if your dates have a ddmmmyyyy format (e.g., 05Mar2021)?
You’ll then need to apply the format below (by changing the ‘m’ to ‘b’):
So your complete Python code would look like this:
You’ll now get the datetime format:
Let’s say that your dates now contain dashes (e.g., ’05-Mar-2021′) .
In that case, simply add those dashes as follows:
Here is the full Python code:
And the result:
Formats with Timestamps
Suppose that your strings contain both the dates and times:
In that case, the format that should be specified is:
So the full Python code would be:
You’ll now see the datetime format:
Now let’s say that the strings contain characters, such as the dash character (“-“) to separate between the date and the time:
In that scenario, the format should include the dash as well:
How to convert string to datetime format in Pandas Python

As a data scientist or software engineer, you may come across situations where you need to work with date and time data in your data analysis or machine learning projects. In such cases, Pandas is one of the most popular Python libraries used for data manipulation and analysis. Pandas provides a powerful and flexible way to work with date and time data, including the ability to convert strings to datetime format. In this article, we will explore how to convert a string to datetime format in Pandas Python.
What is datetime format?
Before diving into the conversion process, let’s first understand what datetime format is. Datetime format is a standard way of representing date and time information in a human-readable format. The datetime format includes various components such as year, month, day, hour, minute, and second. Different programming languages and libraries support different datetime formats, but the most common format is ISO 8601.
Converting string to datetime in Pandas
Pandas provides the to_datetime() method to convert a string to datetime format. The to_datetime() method can handle various date and time formats and returns a datetime object. The syntax for using the to_datetime() method is as follows:
In the above syntax, string is the string that needs to be converted to datetime format, and format is the format of the string. If the format parameter is not specified, the to_datetime() method will try to infer the format automatically.
Example 1: Converting a string to datetime format
Let’s start with a simple example. Suppose we have a string representing a date in the format “YYYY-MM-DD”, and we want to convert it to datetime format. The following code demonstrates how to do this using the to_datetime() method:
In the above example, we first defined a string date_string representing the date “2022-05-12”. We then used the to_datetime() method to convert the string to datetime format and stored the result in the date_time variable. Finally, we printed the date_time variable, which gives us the datetime object.
Example 2: Converting a string with time to datetime format
In some cases, the string may contain both date and time information. For example, the string may be in the format “YYYY-MM-DD HH:MM:SS”. In such cases, we need to specify the format of the string using the format parameter. The following code demonstrates how to convert a string with time to datetime format:
In the above example, we defined a string date_string representing the date and time “2022-05-12 13:30:00”. We then used the to_datetime() method to convert the string to datetime format and specified the format of the string using the format parameter. Finally, we printed the date_time variable, which gives us the datetime object.
Example 3: Converting a column of strings to datetime format
In a real-world scenario, you may have a dataset with a column containing date and time information in string format. In such cases, you can use the apply() method of Pandas to apply the to_datetime() method to the entire column. The following code demonstrates how to convert a column of strings to datetime format:
In the above example, we defined a sample dataframe with two columns Date and Time representing the date and time information in string format. We then combined the Date and Time columns into a single column Datetime . Finally, we applied the to_datetime() method to the Datetime column using the apply() method and specified the format of the string using the format parameter. The result is a new column Datetime containing datetime objects.
In this article, we explored how to convert a string to datetime format in Pandas Python. We learned that Pandas provides the to_datetime() method to convert a string to datetime format, and we can specify the format of the string using the format parameter. We also learned how to apply the to_datetime() method to an entire column of strings in a Pandas dataframe. By mastering these techniques, you can easily work with date and time data in your data analysis or machine learning projects.
About Saturn Cloud
Saturn Cloud is your all-in-one solution for data science & ML development, deployment, and data pipelines in the cloud. Spin up a notebook with 4TB of RAM, add a GPU, connect to a distributed cluster of workers, and more. Join today and get 150 hours of free compute per month.
- Stack Overflow Public questions & answers
- Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
- Talent Build your employer brand
- Advertising Reach developers & technologists worldwide
- Labs The future of collective knowledge sharing
- About the company
New search experience powered by AI
Stack Overflow is leveraging AI to summarize the most relevant questions and answers from the community, with the option to ask follow-up questions in a conversational format.
Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Get early access and see previews of new features.
Python datetime to string
I am trying to convert this:
Instead I am getting this:
- 1 Use my_time.strftime("%Y%m%d.%H%M%S") – Diego Borba yesterday
- 1 Also, check this out . – Diego Borba yesterday
- 1 Does this answer your question? Convert datetime object to a String of date only in Python – Diego Borba yesterday
You most certainly mean
Your initial code use %M (meaning minutes) instead of %m (month). And your example also does! (202354 is quite unrealistic).
And more importantly you used %D (meaning compact date in format 09/25/23 ) instead of %d (day of month).

Your Answer
Sign up or log in, post as a guest.
Required, but never shown
By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct .
Not the answer you're looking for? Browse other questions tagged python datetime or ask your own question .
- The Overflow Blog
- Behind the scenes with OverflowAI Search
- Featured on Meta
- If more users could vote, would they engage more? Testing 1 reputation voting...
- Alpha test for short survey in banner ad slots starting on week of September...
- Temporary policy: Generative AI (e.g., ChatGPT) is banned
- Expanding Discussions: Let's talk about flag reasons
- Collectives Updates to the Community Bulletin in the Right Sidebar
- OverflowAI Search is now available for alpha testing (September 13, 2023)
Hot Network Questions
- Delete list elements above a certain threshold
- Best Practices for running data conduits through basement
- How to get tofu to absorb flavour?
- What does THAT mean here?
- Fantasy children's story where they suspect someone is a vampire
- Is it possible to redefine the limit operator to print Lim, not lim?
- How to simulate decreasing randomness even though randomness is increasing?
- Why we use vector sum to calculate net potential in AC circuits?
- 9 year old ATA red belt got beat at tournament
- Does the term "vapor pressure" even mean anything in an open system?
- Can the Faerie Fire spell be oriented in a small space to not affect allies?
- Custom Element Type Documentation not working or confusing
- In countries using Single Transferable Vote, how are voting results presented?
- Feeling of falling during turbulence
- Aligment of the hightlight in the TikZ figure
- A Trivial Pursuit #12 (Sports and Leisure 2/4): Logic Boat
- LD_PRELOAD does not work and LD_DEBUG shows nothing
- What attracted Abimelech to an old woman in her 80s or 90s?
- How to move forward after microagression allegations against my TA
- Reconstruct an array by successive insertions
- "Premove" in OTB game
- Flaps Cessna 172 breaker tripping
- Lawn: Newly sown turf grows at least twice as fast as the "old" turf
- Do you win a Numeric Mahjong?
Your privacy
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy .

Python Date to String
Chapter: Python Last Updated: 23-07-2023 14:30:05 UTC
- You can use other format codes to represent different date and time components according to your needs.
1 2 3 4
About Us | Terms & Conditions | Privacy Policy
Copyright © 2021 Programiz.org
We Love Servers.
- WHY IOFLOOD?
- DEDICATED SERVERS
Learn Python: Convert datetime to string (With Examples)
Ever felt like a time traveler lost in the realm of Python’s datetime objects? Struggling to convert these datetime objects into strings? Don’t worry, we’ve got you covered. Python provides us with easy-to-use functions to convert datetime objects into strings.
In this comprehensive guide, we will walk you through the process of converting Python datetime to string – from basic usage to more advanced techniques. So, buckle up and get ready to dive into the world of Python datetime conversions!
TL;DR: How Do I Convert Datetime to String in Python?
You can use the strftime() function to convert datetime to a string in Python. Here’s a simple example:
In this example, we’ve imported the datetime module, obtained the current date and time using datetime.now() , and then converted it to a string using the strftime() function. The format string ‘%Y-%m-%d %H:%M:%S’ specifies the output format, which in this case is ‘YYYY-MM-DD HH:MM:SS’.
This is just the tip of the iceberg! Keep reading for more detailed information and advanced usage scenarios.
Table of Contents
Basic Use of strftime() Function in Python
Handling different date and time formats, exploring alternative methods for datetime conversion, troubleshooting common issues in datetime conversion, understanding python’s datetime module and string data type, exploring related concepts, wrapping up:.
In Python, the strftime() function is a built-in method used to convert a datetime object into a string representing date and time under different formats.
The strftime() stands for ‘String Format Time’. It belongs to the datetime and time modules, and it requires a format string to dictate the output format of the date and time.
Let’s see a basic example of how to use the strftime() function:
In this code block, we first import the datetime module. Then, we get the current date and time using datetime.now() . After that, we specify the format in which we want our date and time to be converted into a string. Finally, we use the strftime() function to convert the datetime object into a string.
As you start to delve deeper into Python’s datetime conversions, you’ll find that there are numerous date and time formats to consider. The strftime() function provides a wide range of format codes that allow you to handle different date and time formats.
Let’s take a look at an example where we use different format codes to represent the same datetime object:
In this example, we’ve used three different format specifications for the same datetime object.
The first format is the standard ‘YYYY-MM-DD HH:MM:SS’. The second format changes the date to ‘DD/MM/YYYY’ and adds a comma between the date and time. The third format gives a more verbose output, including the day of the week, the date with a period after the day number, the full month name, the year, and the time in 12-hour format with AM/PM.
The strftime() function provides a great deal of flexibility in handling different date and time formats. However, it’s crucial to use the correct format codes and to understand the output they produce.
While strftime() is a powerful tool for datetime conversion, Python offers alternative methods that can be more suitable in certain scenarios. Two of these methods are isoformat() and __str__() .
Converting Datetime to String Using isoformat()
The isoformat() method returns a string representing the date in ISO 8601 format, which is ‘YYYY-MM-DDTHH:MM:SS’. Let’s see it in action:
In this example, we use isoformat() to convert the datetime object into a string. Note the ‘T’ separator between the date and time in the output.
Converting Datetime to String Using __str__()
The __str__() method is another way to convert datetime to string. It returns a string representing the date and time in the format ‘YYYY-MM-DD HH:MM:SS.ssssss’. Here’s how it works:
In this example, we use __str__() to convert the datetime object into a string. Note the inclusion of microseconds in the output.
While isoformat() and __str__() can be handy, they offer less flexibility compared to strftime() . Both functions have fixed output formats and do not accept format codes. However, they can be more convenient for quick and simple conversions.
The method you choose for converting datetime to string in Python depends on your specific needs and the level of customization you require. If you need a specific format, strftime() is the way to go. For standard formats, isoformat() and __str__() can save you some time.
Converting datetime to string in Python is not always a smooth process. You may encounter issues, especially when dealing with different date and time formats. Let’s discuss some common problems and their solutions.
Handling ‘ValueError’
One of the most common errors during datetime conversion is the ‘ValueError’. This error occurs when you use an incorrect format code in the strftime() function. Here’s an example:
In this example, we’ve used ‘%Q’, which is not a valid format code, leading to a ‘ValueError’. The solution is simple: always ensure you’re using valid format codes with the strftime() function.
Dealing with Different Formats
Another common issue is dealing with different date and time formats. For instance, if you’re working with a 12-hour format, you need to use ‘%I’ for hours instead of ‘%H’. Here’s an example that illustrates this:
In this example, we’ve used ‘%I’ for hours and ‘%p’ for AM/PM to handle the 12-hour format. Always ensure you’re using the correct format codes for your specific needs.
To fully grasp the conversion of datetime to string in Python, it’s crucial to understand the basics of Python’s datetime module and string data type.
Python’s Datetime Module
Python’s datetime module supplies classes to manipulate dates and times. The datetime class within this module is used to represent a point in time. Here’s a simple example of its usage:
In this example, we use the datetime.now() function to get the current date and time. The output is a datetime object representing the current date and time.
Python’s String Data Type
In Python, strings are sequences of character data. The string type in Python is called ‘str’. String literals can be enclosed by either double or single quotes, although single quotes are more commonly used. Here’s a simple string assignment:
In this example, we assign a string to the variable ‘message’ and then print it. The output is the string ‘Hello, Python!’.
Date and Time Formats
When converting datetime to string, it’s important to understand different date and time formats. The strftime() function uses format codes to specify the output format.
For instance, ‘%Y’ represents the full year, ‘%m’ represents the month, ‘%d’ represents the day, ‘%H’ represents the hour (24-hour format), ‘%M’ represents the minute, and ‘%S’ represents the second. You can combine these format codes to create a format that suits your needs.
By understanding Python’s datetime module, string data type, and different date and time formats, we can better understand the process of converting datetime to string in Python.
Once you’ve mastered the conversion of datetime to string in Python, you might want to explore related concepts like handling time zones in Python , performing date and time arithmetic , and working with timestamps . These concepts will further expand your understanding and capabilities in dealing with date and time in Python.
Throughout this guide, we’ve journeyed from the basics to the advanced aspects of converting datetime to string in Python. We’ve explored the strftime() function’s usage, which offers high flexibility with customizable output formats. We’ve also discussed common issues like handling ‘ValueError’ and dealing with different date and time formats, providing solutions and workarounds for each.
We dove into alternative approaches such as isoformat() and __str__() , both offering less flexibility but proving convenient for quick conversions with standard formats. Here’s a quick comparison of these methods:
Remember, the method you choose depends on your specific needs and the level of customization you require. As always, happy coding and continue exploring the vast world of Python!
About Author
Gabriel Ramuglia
Gabriel is the owner and founder of IOFLOOD.com , an unmanaged dedicated server hosting company operating since 2010. Gabriel loves all things servers, bandwidth, and computer programming and enjoys sharing his experience on these topics with readers of the IOFLOOD blog.
Related Posts


IMAGES
VIDEO
COMMENTS
Introduction The Python datetime and time modules both include a strptime () class method to convert strings to objects. In this article, you'll use strptime () to convert strings into datetime and struct_time () objects. Converting a String to a datetime object using datetime.strptime () The syntax for the datetime.strptime () method is:
5 Answers Sorted by: 8 You can use datetime module like this example: import datetime date = "2018-05-08" final = datetime.datetime.strptime (date, '%Y-%m-%d').strftime ('%Y-%m-%dT%H:%M:%S.%f') print (final) Output: 2018-05-08T00:00:00.000000 For more details visit datetime 's documentation Share Improve this answer Follow
2 Answers Sorted by: 183 The particular format for strptime: datetime.datetime.strptime (string_date, "%Y-%m-%d %H:%M:%S.%f") #>>> datetime.datetime (2013, 9, 28, 20, 30, 55, 782000) Share Improve this answer Follow answered Sep 28, 2013 at 15:06 Veedrac 58.4k 15 112 169 1 What platforms is %f supported on? - Jonathan Jul 9, 2015 at 2:59
10 Answers Sorted by: 274 datetime module could help you with that : datetime.datetime.strptime (input_date_string, input_format).strftime (output_format) For the specific example you could do : >>> from datetime import datetime >>> datetime.strptime ('Mon Feb 15 2010', '%a %b %d %Y').strftime ('%d/%m/%Y') '15/02/2010'
Parse () can be used to convert a Python string to date-time format. The only parameter used is the string. Example: The program imports the dateutil library's parser module, for converting string to datetime which has a function for parsing date and time strings.
# How to Convert a String to datetime in Python from datetime import datetime # Example 1: Date in format "YYYY-MM-DD" date_string_1 = "2021-09-01" format_1 = "%Y-%m-%d" date_1 = datetime.strptime (date_string_1, format_1) print (date_1) # Example 2: Date and time in format "YYYY/MM/DD hh:mm:ss" date_string_2 = "2021/09/01 14:30:00" format_2 = "...
OpenAI 3. datetime.datetime This class represents a date and time and provides methods for working with both. It combines the functionality of the date and time classes. It is commonly used in data analysis tasks that involve time-series data with a high temporal resolution, such as hourly or minute-level data.
The solution to this problem is to parse (or convert) the string object into a datetime object so Python can recognized it as a date. And then you can extract any underlying attributes you want to get from it. This tutorial will teach you how to convert a string to a datetime object in Python. Without further ado, let's get started.
In this guide - we'll take a look at how to convert a string date/time into a datetime object in Python, using the built-in datetime module, but also third-party modules such as dateutil, arrow and Maya, accounting for time zones. Converting Strings Using datetime
05 Jan 2021 Python doesn't have the date as built-in data type. However, the datetime module in the standard library defines date, time, and datetime classes using which date and time related processing can be done. Objects of these classes are created by providing integer arguments as following:
Module zoneinfo Concrete time zones representing the IANA time zone database. Package dateutil Third-party library with expanded time zone and parsing support. Package DateType Third-party library that introduces distinct static types to e.g. allow static type checkers to differentiate between naive and aware datetimes. Aware and Naive Objects ¶
4 Answers Sorted by: 159 Use datetime.datetime.strptime () and call .time () on the result: >>> datetime.datetime.strptime ('03:55', '%H:%M').time () datetime.time (3, 55) The first argument to .strptime () is the string to parse, the second is the expected format. Share Follow edited Feb 9, 2022 at 16:23 answered Jan 12, 2013 at 17:09
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).
Scikit-Learn Scipy Training Course YouTube How to Convert a String to DateTime in Python? June 18, 2023by Bijay Kumar This Python tutorial explains, how to convert a string to datetime in Python. I will also show you, how to convert string to datetime with timezone in Python.
8 Answers Sorted by: 292 The datetime class has a method strftime. The Python docs documents the different formats it accepts: strftime () and strptime () Behavior For this specific example, it would look something like: my_datetime.strftime ("%B %d, %Y") Share Improve this answer Follow edited 2 days ago wjandrea
This function converts a scalar, array-like, Series or DataFrame /dict-like to a pandas datetime object. Parameters: argint, float, str, datetime, list, tuple, 1-d array, Series, DataFrame/dict-like The object to convert to a datetime. If a DataFrame is provided, the method expects minimally the following columns: "year" , "month", "day".
This recipe demonstrates how to convert date strings to the datetime format. datetime.strptime is the primary routine for parsing strings into datetimes. datetime.strptime(date_string, format) Once you have your value in datetime objects, you can then extract specific components of the date such as the month, day, or year, all of which are ...
Steps to Convert Strings to Datetime in Pandas DataFrame Step 1: Collect the Data to be Converted To begin, collect the data that you'd like to convert to datetime. For example, here is a simple dataset about 3 different dates (with a format of yyyymmdd ), when a store might be opened or closed: Step 2: Create a DataFrame
import pandas as pd # Define the string to be converted date_string = '2022-05-12' # Convert string to datetime date_time = pd.to_datetime(date_string) # Print the result print(date_time) Output: 2022-05-12 00:00:00 In the above example, we first defined a string date_string representing the date "2022-05-12".
Python datetime to string. Ask Question Asked today. Modified today. Viewed 11 times -1 I am trying to convert this: ... Convert datetime object to a String of date only in Python - Diego Borba. 30 mins ago. Add a comment | 1 Answer Sorted by: Reset to default 2 You most certainly mean ...
Use the strftime () method to convert the datetime object to a string, specifying the format you desire. The format codes are used to represent different parts of the date and time. Here are some common format codes: %Y: Year with century as a decimal number (e.g., 2023). %m: Month as a zero-padded decimal number (e.g., 07).
You can use the strftime () function to convert datetime to a string in Python. Here's a simple example: from datetime import datetime now = datetime.now() string = now.strftime('%Y-%m-%d %H:%M:%S') print(string) # Output: # '2022-06-30 15:30:00'