English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this article, you will learn how to manipulate dates and times in Python through examples.
Python has a module nameddatetimemodule, used for processing dates and times. Before we delve deeper, let's create some simple programs related to dates and times.
import datetime datetime_object = datetime.datetime.now() print(datetime_object)
When you run the program, the output will be similar to:
2020-04-13 17:09:49.015911
Here, we use the import datetime statement to importdatetimemodule.
A class defined in the datetime module is the datetime class. Then, we use the now() method to create a datetime object containing the current local date and time.
import datetime date_object = datetime.date.today() print(date_object)
When you run the program, the output will be similar to:
2020-04-13
In this program, we used the today() method defined in the date class to get a date object containing the current local date.
What's inside datetime?
We can usedir()function to get a list of all module attributes.
import datetime print(dir(datetime))
The output when running the program is:
['MAXYEAR', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_divide_and_round', 'date', 'datetime', 'datetime_CAPI', 'time', 'timedelta', 'timezone', 'tzinfo']
Common classes in the datetime module are:
date class
time class
datetime class
timedelta class
You can instantiate a date object from the date class. The date object represents a date (year, month, and day).
import datetime d = datetime.date(2019, 4, 13:", s print(d)
The output when running the program is:
2019-04-13
If you are curious, the date() in the above example is the constructor of the date class. The constructor has three parameters: year, month, and day.
variableais a date object.
We can only import the date class from the datetime module. It is like this:
from datetime import date a = date(2019, 4, 13:", s print(a)
You can use a class method named today() to create a date object containing the current date. The method is as follows:
from datetime import date today = date.today() print("Current date =", today)
We can also create a date object from a timestamp. Unix timestamp is the number of seconds from a specific date to UTC1970 years1month1seconds between two days. You can use the fromtimestamp() method to convert a timestamp to a date.
from datetime import date timestamp = date.fromtimestamp(1576244364:", s print("date =", timestamp)
The output when running the program is:
date = 2019-12-13
We can easily get the year, month, day, day of the week, etc. from the date object. It is like this:
from datetime import date # Today's date object today = date.today() print("Current year:", today.year) print("Current month:", today.month) print("Current day:", today.day)
Time objects instantiated from the time class represent local time.
from datetime import time # time(hour = 0, minute = 0, second = 0) a = time() print("a =", a) # time(hour, minute and second) b = time(11, 34, 56:", s print("b =", b) # time(hour, minute and second) c = time(hour = 11, minute = 34, second = 56:", s print("c =", c) # time(hour, minute, second, microsecond) d = time(11, 34, 56, 234566:", s print("d =", d)
The output when running the program is:
a = 00:00:00 b = 11:34:56 c = 11:34:56 d = 11:34:56.234566
After creating the time object, you can easily print its properties, such ashour,minuteetc.
from datetime import time a = time(11, 34, 56:", s print("hour=", a.hour) print("minute=", a.minute) print("second=", a.second) print("microsecond=", a.microsecond)
When running the example, the output will be:
hour= 11 minute= 34 second= 56 microsecond= 0
Note that we have not passedmicrosecondTherefore, it will print the default value 0.
The datetime module has a class named date that can contain parameters fromdateandtimeinformation of the object.
from datetime import datetime # datetime(year, month, day) a = datetime(2019, 11, 28:", s print(a) # datetime(year, month, day, hour, minute, second, microsecond) b = datetime(2019, 11, 28, 23, 55, 59, 342380) print(b)
The output when running the program is:
2019-11-28 00:00:00 2019-11-28 23:55:59.342380
The first three parameters year, month, and day of the datetime() constructor are required.
from datetime import datetime a = datetime(2019, 12, 28, 23, 55, 59, 342380) print("Year = ", a.year) print("Month = ", a.month) print("Day = ", a.day) print("Hour = ", a.hour) print("Month = ", a.minute) print("Timestamp = ", a.timestamp())
The output when running the program is:
Year = 2019 Month = 12 Day = 28 Hour = 23 Month = 55 Timestamp = 1577548559.34238
timedelta objects represent the time difference between two dates or times.
from datetime import datetime, date t1 = 2018, month = 7, day = 12:", s t2 = 2017, month = 12, day = 23:", s t3 =1 - t2 print("t3 = "3:", s t4 = 2018, month = 7, day = 12, hour = 7, minute = 9, second = 33:", s t5 = 2019, month = 6, day = 10, hour = 5, minute = 55, second = 13:", s t6 =4 - t5 print("t6 = "6:", s print("type of t3 =3)) print("type of t6 =6))
The output when running the program is:
t3 = 201 days, 0:00:00 t6 = -333 days, 1:14:20 type of t3 = type of t6 =
Note thatt3andt6are of type <class 'datetime.timedelta'>.
from datetime import timedelta t1 = 2, days = 5hours = 1, seconds = 33:", s t2 = 4hours = 11, minutes = 4, seconds = 54:", s t3 =1 - t2 print("t3 = "3:", s
The output when running the program is:
t3 = 14 days, 13:55:39
Here, we create two timedelta objectst1andt2The number of days directly between them is printed on the screen.
from datetime import timedelta t1 = 33:", s t2 = 54:", s t3 =1 - t2 print("t3 = "3:", s print("t3 = "3))
The output when running the program is:
t3 = -1 day, 23:59:39 t3 = 0:00:21
You can use the total_seconds() method to get the total number of seconds in a timedelta object.
from datetime import timedelta t = timedelta(days = 5hours = 1, seconds = 33, seconds = 233423:", s , microseconds =
The output when running the program is:
print("total seconds =", t.total_seconds()) 435633.233423
total seconds =+You can also use
Python format date and time / # mm / The representation of dates and times may vary in different places, organizations, etc. In the United States, mm is used / # dd / yyyy is more common, while in the UK dd is used
yyyy is more common.
String date and time object
from datetime import datetime :使用strftime()格式化日期 # current date and time now = datetime.now() t = now.strftime("%H:%M:%S") s1 print("time:", t)/%d/= now.strftime("%d = now.strftime("%m/# mm/mm YY H:M:S format1print("s1:", s s2 dd/%m/= now.strftime("%d %Y, %H:%M:%S")/# dd/mm YY H:M:S format2print("s2:", s
When you run the program, the output will be similar to:
)4:34:52 s1: 12/26/2018time: 04:34:52 s2: 26/12/2018time: 04:34:52
, 0
In the above program,t,s1ands2is a string.
%Y -years [0001,...2018,2019,...9999]
%m -months [01,02,...11,12]
%d -days [01,02,...30,31]
%H -hours [00, 01,...22,23
%M -minutes [00, 01,...58,59]
%S -seconds [00, 01,...58,59]
For more information on strftime() code and setting its format, please visit:Python strftime().
strptime() method creates a datetime object from a given string (representing a date and time).
from datetime import datetime date_string = "21 June, 2018" print("date_string =", date_string) date_object = datetime.strptime(date_string, '%d %B, %Y') print("date_object =", date_object)
The output when running the program is:
date_string = 21 June, 2018 date_object = 2018-06-21 00:00:00
The strptime() method has two parameters:
String representing date and time
Is equivalent to the format code of the first parameter
By the way, the %d, %B, and %Y format codes are used for day, month (full name), and year, respectively.
VisitPython strptime()For more information.
Assuming you are working on a project that needs to display the date and time according to its time zone. We recommend using third-partypytz moduleInstead of handling the time zone yourself.
from datetime import datetime import pytz local = datetime.now() print("Local:", local.strftime("%m/%d/"%Y, %H:%M:%S") tz_NY = pytz.timezone('America/New_York') datetime_NY = datetime.now(tz_NY) print("NY:", datetime_NY.strftime("%m/%d/"%Y, %H:%M:%S") tz_London = pytz.timezone('Europe/London') datetime_London = datetime.now(tz_London) print("London:", datetime_London.strftime("%m/%d/"%Y, %H:%M:%S")
When you run the program, the output will be similar to:
Local time: 2018-12-20 13:10:44.260462 America/New_York time: 2018-12-20 13:10:44.260462 Europe/London time: 2018-12-20 13:10:44.260462
Here,datetime_NYanddatetime_LondonIs a datetime object containing the current date and time with their respective time zones.