English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Dans cet article, vous apprendrez comment manipuler les dates et les heures en Python à travers des exemples.
Python a un nom appelédatetimele module, utilisé pour traiter les dates et les heures. Avant de plonger dans les détails, créons quelques programmes simples liés à la date et à l'heure.
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
Ici, nous utilisons l'instruction import datetime pour importerdatetimemodule.
Une classe définie dans le module datetime est la classe datetime. Ensuite, nous utilisons la méthode now() pour créer un objet datetime contenant la date et l'heure locales actuelles.
import datetime date_object = datetime.date.today() print(date_object)
When you run the program, the output will be similar to:
2020-04-13
Dans ce programme, nous avons utilisé la méthode today() définie dans la classe date pour obtenir un objet date contenant la date locale actuelle.
Qu'y a-t-il dans datetime ?
Nous pouvons utiliserdir()fonction pour obtenir une liste de toutes les propriétés du module.
import datetime print(dir(datetime))
When running the program, the output is:
['MAXYEAR', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_divide_and_round', 'date', 'datetime', 'datetime_CAPI', 'time', 'timedelta', 'timezone', 'tzinfo']
Les classes couramment utilisées dans le module datetime sont :
classe date
classe time
classe datetime
classe timedelta
Vous pouvez instancier un objet date à partir de la classe date. Un objet date représente une date (année, mois et jour).
import datetime d = datetime.date(2019, 4, 13) print(d)
When running the program, the output is:
2019-04-13
Si vous voulez savoir, le date() de l'exemple ci-dessus est le constructeur de la classe date. Le constructeur a trois paramètres : année, mois et jour.
variableaest un objet date.
Nous ne pouvons importer que la classe date du module datetime. Voici comment :
from datetime import date a = date(2019, 4, 13) print(a)
Vous pouvez utiliser une méthode de classe nommée today() pour créer un objet date contenant la date actuelle. Voici la méthode :
from datetime import date today = date.today() print("Date actuelle =", today)
Nous pouvons également créer un objet date à partir d'un timestamp. Le timestamp Unix est le nombre de secondes écoulées depuis une date spécifique jusqu'à UTC1970 an1mois1les secondes entre deux jours. Vous pouvez utiliser la méthode fromtimestamp() pour convertir un timestamp en date.
from datetime import date timestamp = date.fromtimestamp(1576244364) print("日期 =", timestamp)
When running the program, the output is:
日期 = 2019-12-13
我们可以轻松地从日期对象获取年,月,日,星期几等。就是这样:
from datetime import date # 今天的日期对象 today = date.today() print("当前年:", today.year) print("当前月:", today.month) print("当前日:", today.day)
从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) print("b =", b) # time(hour, minute and second) c = time(hour = 11, minute = 34, seconde = 56) print("c =", c) # time(hour, minute, second, microsecond) d = time(11, 34, 56, 234566) print("d =", d)
When running the program, the output is:
a = 00:00:00 b = 11:34:56 c = 11:34:56 d = 11:34:56.234566
创建time对象后,您可以轻松打印其属性,例如小时,分钟等。
from datetime import time a = time(11, 34, 56) print("小时=", a.hour) print("分钟=", a.minute) print("秒=", a.second) print("微秒=", a.microsecond)
运行示例时,输出将是:
小时= 11 分钟= 34 秒= 56 微秒= 0
注意,我们还没有传递微秒参数。因此,将打印其默认值0。
datetime模块有一个名为date的class类,可以包含来自dateandtime对象的信息。
from datetime import datetime #datetime(year, month, day) a = datetime(2019, 11, 28) print(a) # datetime(year, month, day, hour, minute, second, microsecond) b = datetime(2019, 11, 28, 23, 55, 59, 342380) print(b)
When running the program, the output is:
2019-11-28 00:00:00 2019-11-28 23:55:59.342380
Les trois premiers paramètres year, month et day du constructeur datetime() sont obligatoires.
from datetime import datetime a = datetime(2019, 12, 28, 23, 55, 59, 342380) print("Année =", a.year) print("Mois =", a.month) print("Jour =", a.day) print("Heure =", a.hour) print("Mois =", a.minute) print("Horodatage =", a.timestamp())
When running the program, the output is:
Année = 2019 Mois = 12 Jour = 28 Heure = 23 Mois = 55 Horodatage = 1577548559.34238
Le timedelta objet représente la différence entre deux dates ou heures.
from datetime import datetime, date t1 = date(année = 2018, mois = 7, jour = 12) t2 = date(année = 2017, mois = 12, jour = 23) t3 = t1 - t2 print("t3 = ", t3) t4 = datetime(année = 2018, mois = 7, jour = 12, heure = 7, minute = 9, seconde = 33) t5 = datetime(année = 2019, mois = 6, jour = 10, heure = 5, minute = 55, seconde = 13) t6 = t4 - t5 print("t6 = ", t6) print("type de t3 = ", type(t3)) print("type de t6 = ", type(t6))
When running the program, the output is:
t3 = 201 jours, 0:00:00 t6 = -333 jours, 1:14:20 type de t3 = <class 'datetime.timedelta'> type de t6 = <class 'datetime.timedelta'>
Attention,t3andt6sont de type <class 'datetime.timedelta'>.
from datetime import timedelta t1 = timedelta(semaines = 2, jours = 5, heures = 1, seconds = 33) t2 = timedelta(jours = 4, heures = 11, minutes = 4, seconds = 54) t3 = t1 - t2 print("t3 = ", t3)
When running the program, the output is:
t3 = 14 jours, 13:55:39
Ici, nous avons créé deux timedelta objetst1andt2,les différences directes en jours sont affichées à l'écran.
from datetime import timedelta t1 = timedelta(secondes = 33) t2 = timedelta(secondes = 54) t3 = t1 - t2 print("t3 = ", t3) print("t3 = ", abs(t3))
When running the program, the output is:
t3 = -1 jour, 23:59:39 t3 = 0:00:21
Vous pouvez obtenir le nombre total de secondes du timedelta objet en utilisant la méthode total_seconds().
from datetime import timedelta t = timedelta(jours = 5, heures = 1, seconds = 33, microseconds = 233423) print("total seconds =", t.total_seconds())
When running the program, the output is:
total seconds = 435633.233423
您还可以使用+运算符找到两个日期和时间的总和。同样,您可以将timedelta对象乘以整数和浮点数。
日期和时间的表示方式在不同的地方,组织等中可能有所不同。在美国,使用mm / dd / yyyy更为常见,而在英国使用dd / mm / yyyy更为常见。
Python有strftime()和strptime()方法来处理这个问题。
strftime()方法是在date、datetime和time类下面定义的。该方法根据给定的日期、日期时间或时间对象创建格式化的字符串。
from datetime import datetime # current date and time now = datetime.now() t = now.strftime("%H:%M:%S") print("time:", t) s1 = now.strftime("%m/%d/%Y, %H:%M:%S") # mm/dd/YY H:M:S format print("s1:", s1) s2 = now.strftime("%d/%m/%Y, %H:%M:%S") # dd/mm/YY H:M:S format print("s2:", s2)
When you run the program, the output will be similar to:
time: 04:34:52 s1: 12/26/2018, 04:34:52 s2: 26/12/2018, 04:34:52
这里%Y,%m,%d,%H等都是格式代码。strftime()方法采用一个或多个格式代码,并根据该代码返回格式化的字符串。
在上面的程序中,t,s1ands2是字符串。
%Y -年[0001,...,2018,2019,...,9999]
%m -月[01,02,...,11,12]
%d -天[01,02,...,30,31]
%H -小时[00,01,...,22,23
%M -分钟[00,01,...,58,59]
%S -秒[00,01,...,58,59]
要了解有关strftime()代码并设置其格式的更多信息,请访问:strftime() en Python。
strptime()方法从一个给定的字符串(表示日期和时间)创建一个datetime对象。
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)
When running the program, the output is:
date_string = 21 June, 2018 date_object = 2018-06-21 00:00:00
The strptime() method has two parameters:
representing the date and time string
is equivalent to the format code of the first parameter
By the way, the format codes %d, %B, and %Y are used for day, month (full name), and year, respectively.
Visitstrptime() en PythonFor more information.
Assuming you are working on a project that needs to display the date and time according to its time zone.pytz 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.