Formatting dates is one of the topics that every newbie faces when working with Python. When working with time-series data, formatting data and time is one of the most important topics for you. In this article, I’ll walk you through how to format dates using Python.
Format Dates using Python
To work with the date and time, we need to use the DateTime module in Python, and to format the date and time, we need to use the same kind of formatting methods that we use to format strings. So, before we format a date or time, let’s take a quick look at how the DateTime module works in Python:
from datetime import datetime a = datetime(2021, 10, 2, 0, 0, 0) b = datetime(2021, 10, 10, 20, 59, 59)
So the arguments of “datetime” are (Year, Month, Date, Hours, Minutes, Seconds). So now let’s have a quick look at what we get if we subtract these two dates:
output = b-a print(output)
Output: 8 days, 20:59:59
So we got 8 days, 20:59:59, as an output. Now let’s see how to get only days and seconds:
Now let’s have a look at how to format dates like we format strings using Python:
string_datetime = datetime(2021, 10, 2, 0, 0, 0) string_format = '%b %d %Y %H:%M:%S' string_output = datetime.strftime(string_datetime, string_format) print(string_output)
Output: Oct 02 2021 00:00:00
Also, Read – 200+ Machine Learning Projects Solved and Explained.
So this is how we do date and time formating using Python. There is not much difference between string and date formating. I hope you liked this article on how to format dates using Python. Feel free to ask your valuable questions in the comments section below.