How to use datetime module in Python
One of the most important advantages of the Python programming language is the presence of rich and functional libraries (modules) in this language. Python is one of the few programming languages for which there is a useful library in every field. Learning different Python libraries will be of great help in your programming progress. In this article, we are going to teach you how to use datetime module in Python with several different programs. The datetime module is one of the important Python libraries. If you are interested in these topics, stay tuned.
The first program
For the first program, we give a simple example and write a program that receives the current date as separate values of a year, month, day, hour, minute, and second, and at the end, we print it.
To start working with the datetime library in Python for this program and other programs that we will write, we must first import the datetime module at the beginning of the programs with the import command. like this:
import datetime
Next, we need to get the current date. For this purpose, we use the today() function in the datetime class. like this:
import datetime
now = datetime.datetime.today()
...
Now, using the now variable, we receive all its contents separately as follows:
...
now = datetime.datetime.today()
mm = str(now.month)
dd = str(now.day)
yyyy = str(now.year)
hour = str(now.hour)
mi = str(now.minute)
ss = str(now.second)
...
Each of the above variables represents the year, month, day, hour, minute, and second respectively. At the end, we print the desired output using the print command.
print (mm + "/" + dd + "/" + yyyy + " " + hour + ":" + mi + ":" + ss)
Our complete and one-place program along with its output is as follows:
import datetime
now = datetime.datetime.today()
mm = str(now.month)
dd = str(now.day)
yyyy = str(now.year)
hour = str(now.hour)
mi = str(now.minute)
ss = str(now.second)
print (mm + "/" + dd + "/" + yyyy + " " + hour + ":" + mi + ":" + ss)
6/16/2020 12:23:27
In the rest of this article, we will see how we can have the desired output for the date format by writing a line of code.
The second program
Our second program will be a program that receives the user’s age from input and prints his year of birth. We import the datetime module first:
import datetime
To find the user’s year of birth from his age, we need to subtract the age from the year we are in, to get the year of birth. In the datetime module, we can get the current date and time by using the now() function in its datetime class. So here we store the date and time in a variable. like this:
import datetime
now = datetime.datetime.now()
...
If we now execute the now variable with the print command, our output is as follows:
2020-06-15 22:59:03.274304
We don’t need this exact date and time, we just need the desired year. For this, we can get only the year using the year attribute. So, in the continuation of writing the program, we receive the age from the user. like this:
import datetime
now = datetime.datetime.now()
age = float(input('What is your age? '))
...
Now it is enough to subtract the year we are in from the age to get the year of birth. As we said, we use the year attribute to have the year. like this:
...
year_born = int(now.year - age)
...
Finally, to print the answer, we need to print the year_born variable in the output using the print() function. like this:
...
year_born = int(now.year - age)
print ("Awesome! you were born in ", year_born)
Our complete code is as follows. If we enter the input age as 25, see the output of the code below.
import datetime
now = datetime.datetime.now()
age = float(input('What is your age? '))
year_born = int(now.year - age)
print ("Awesome! you were born in ", year_born)
What is your age? 25
Awesome! you were born in 1995
The third program
For the third program, we will write a program that displays the date of the day in the way we like. For this program, we include the datetime module at the beginning of the code. We can use “as” command to change the name of the library to our desired form. like this:
import datetime as dt
...
This time we get today’s date using the today() function in the date class.
import datetime as dt
today_date = dt.date.today()
...
If we now print the today_date variable, our output is as follows:
2020-06-16
As we promised in the first program, it’s time to write our desired output format without additional code. In order to print the date in the desired form with one line of code, we use the strftime() function. like this:
print(today_date.strftime("The Current Date is :\n\n%A %B %d, %Y"))
To learn more about other formatting of the strftime function, see Python’s strftime directives article. You can see the completed program and its output below.
import datetime as dt
today_date = dt.date.today()
print(today_date.strftime("The Current Date is :\n\n%A %B %d, %Y"))
Tuesday June 16, 2020
The fourth program
We want to write a program that searches the date that includes the year, month, and day and finds and prints the dates that are in Palindrome form for us. For example 11.02.2011
This time, we import the datetime module with another method in which all classes are imported. As follows:
from datetime import *
Next, we search from 01.01.1900 to 31.12.2020. So we enter the values like this:
from datetime import *
start = "01.01.1900"
end = "31.12.2020"
...
As you can see, the date we wrote is considered a string and we have to convert it into a date format. For this purpose, we use the strptime() function in the datetime class. like this:
...
start = "01.01.1900"
end = "31.12.2020"
startd = datetime.strptime(start, "%d.%m.%Y")
endd = datetime.strptime(end, "%d.%m.%Y")
...
Now it’s time to scroll through the desired date range with a for loop and find the Palindrome of dates. But before the iteration loop, we can print a statement that shows what our output is. The range of our loop is from zero to the number of days between two dates. like this:
...
startd = datetime.strptime(start, "%d.%m.%Y")
endd = datetime.strptime(end, "%d.%m.%Y")
print("Palindrome dates:")
for i in range((endd-startd).days):
...
We add one day to our start date inside the loop using the timedelta function. As follows:
...
print("Palindrome dates:")
for i in range((endd-startd).days):
startd += timedelta(days = 1)
...
If we want to compare the date with its opposite, it should be in such a way that it does not have any marks or spaces. For this purpose, we use the strftime() function. like this:
...
print("Palindrome dates:")
for i in range((endd-startd).days):
startd += timedelta(days = 1)
dstr = datetime.strftime(startd, "%d%m%Y")
...
Now, to get what the program wants, it must compare the date with its opposite with an if and print it if the condition is met. like this:
...
dstr = datetime.strftime(startd, "%d%m%Y")
if dstr == dstr[::-1]:
print(dstr[:2] + "." + dstr[2:4] + "." + dstr[4:])
...
Our desired program was written. You can see the complete code and a part of the program as well as the output of the program below:
from datetime import *
start = "01.01.1900"
end = "31.12.2020"
startd = datetime.strptime(start, "%d.%m.%Y")
endd = datetime.strptime(end, "%d.%m.%Y")
print("Palindrome dates:")
for i in range((endd-startd).days):
startd += timedelta(days = 1)
dstr = datetime.strftime(startd, "%d%m%Y")
if dstr == dstr[::-1]:
print(dstr[:2] + "." + dstr[2:4] + "." + dstr[4:])
Palindrome dates:
10.02.2001
20.02.2002
01.02.2010
11.02.2011
21.02.2012
02.02.2020
The fifth program
We are going to write a program that receives a date from the input and specifies the number of days of a person’s life until that date and prints it in the output. Print a suitable message if the person is not born by that date.
In this program, we have a date as the year of birth of a person (for example 24/06/1994), then we need to receive a date from the input, so that if he was born on this date, the number of days of his life until print that date. Otherwise, print the message “You are not yet born on this date”.
According to the previous programs, we import the datetime module.
import datetime as dt
Next, we store the date of birth in a variable and then receive the user’s desired date with the input command. In order to have a standard format for receiving dates, we provide the input date format for users as an example. As follows:
import datetime as dt
year_born = dt.date(1982,2,14)
input_year = input('Enter your Date:(e.g. 1990.05.11) ')
...
Now, in order to convert the input date from string to date format, we use the strptime() function as in the previous program. Note that, like the format you receive the date string, specify the year, month, and day order in the strptime function. like this:
...
input_year = input('Enter your Date:(e.g. 1990.05.11) ')
syear = dt.datetime.strptime(input_year, "%Y.%m.%d")
...
Now we need to subtract the given date from the date of birth and store the result in a variable. Because the strptime() function outputs the date and time, we use the date function to filter only the date. With the help of the days attribute, our output will only display the number of days.
...
year_born = dt.date(1982,2,14)
input_year = input('Enter your Date:(e.g. 1990.05.11) ')
syear = dt.datetime.strptime(input_year, "%Y.%m.%d")
days_life = (syear.date()- year_born).days
...
At the end, we check the days_life variable with an if-else condition and if its smaller value is equal to zero, we give the message “You have not been born on this date” and otherwise we print the number of days obtained. like this:
...
days_life = (syear.date()- year_born).days
if days_life <= 0:
print('You were not born on this date.')
else:
print('It\'s been {} days from your date of birth to input date'.format(days_life))
This program is also completed, and you can see its complete code below. See the output of the program if the input date is correct.
import datetime as dt
year_born = dt.date(1982,2,14)
input_year = input('Enter your Date:(e.g. 1990.05.11) ')
syear = dt.datetime.strptime(input_year, "%Y.%m.%d")
days_life = (syear.date()- year_born).days
if days_life <= 0:
print('You were not born on this date.')
else:
print('It\'s been {} days from your date of birth to input date'.format(days_life))
Enter your Date (e.g. 1990.05.11): 2020.06.16
It’s been 14002 days from your date of birth to input date
Conclusion
We tried to teach you how to use datetime module in Python with some short and concise programs. This is only a small part of the capabilities of this library, and you can work with other important classes and functions of this library to practice and learn more.
Libraries in Python are the most attractive and useful feature that Python and other programmers have made publicly available to everyone to avoid repetitive work. A professional programmer owes his most progress to familiarity with various libraries. So you too, to be successful in programming, know the important Python libraries. We hope that the written content will be useful for you. If you have any questions or comments about this, we will be happy to share them with us and W3camps‘ users.