Aller au contenu

Date

On importe le module datetime.

from datetime import datetime

Obtenir l'heure courante:

>>> maintenant = datetime.now()
>>> maintenant
datetime.datetime(2019, 3, 2, 6, 57, 24, 532139)

# datetime(année, mois, jour, heure, minute, seconde, microseconde, fuseau horaire)

>>> maintenant.year
2019
>>> maintenant.month
3
>>> maintenant.day
2
>>> maintenant.hour
6
>>> maintenant.minute
57
>>> maintenant.second
24
>>> maintenant.microsecond
532139
>>> maintenant.isocalendar
<built-in method isocalendar of datetime.datetime object at 0x104900b70>

>>> maintenant.date()
datetime.date(2019, 3, 2)
>>> maintenant.time()
datetime.time(6, 57, 24, 532139)

Créer une date:

# année, mois, jour sont obligatoires
>>> a = datetime(2001, 1, 1)
>>> a.year
2001

Durée:

>>> duree = datetime.now() - datetime(2001, 1, 1)
>>> duree
datetime.timedelta(days=6634, seconds=26875, microseconds=353545)

>>> duree.days
6634
>>> duree.total_seconds()
573204475.353545

Format d'affichage:

>>> maintenant = datetime.now()
>>> maintenant
datetime.datetime(2019, 3, 2, 7, 50, 30, 756453)

>>> maintenant_US = datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')
>>> maintenant_US
'2019-03-02 07:49:12.627321'

>>> maintenant_FR = datetime.now().strftime('%d-%m-%Y %H:%M:%S')
>>> maintenant_FR
'02-03-2019 07:53:05'

Liste des formats

Calendrier:

>>> import calendar
>>> calendar.mdays  # nb de. jours dans le mois
[0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
>>> calendar.isleap(2020)   # année bisextile ?
True
>>> calendar.weekday(1966, 8, 31)   # jour précis d'une date (2 => mercredi)
2

Timestamp:

Récupérer le timestamp courant:

>>> from datetime import datetime
>>> import calendar
>>> d = datetime.now()
>>> ts = calendar.timegm(d.utctimetuple())
>>> ts
1551516334
>>> import time
>>> ts = time.time()
>>> ts
1551511030.9611452
>>> import datetime
>>> ts = datetime.datetime.now().timestamp()
>>> ts
1551511138.821511

# equivalent
>>> from datetime import datetime
>>> ts = datetime.now().timestamp()
>>> ts
1551511979.337509
import calendar, time
>>> ts = calendar.timegm(time.gmtime())
>>> ts
1551511394

Récupérer une date depuis un timestamp:

# heure utc
>>> d = datetime.utcfromtimestamp(ts)
>>> d
datetime.datetime(2019, 3, 2, 8, 53, 3)
# heure LOCALE
>>> e = datetime.fromtimestamp(ts)
>>> e
datetime.datetime(2019, 3, 2, 9, 53, 3)

Dernière mise à jour: March 15, 2019