Notes Python - date - datetime

AM/PM

AM	ante meridiem
PM	post meridiem
import datetime #from datetime import datetime format_date='%Y-%m-%d %I:%M %p' date1=datetime.datetime(2023, 9, 25, 11, 59, 0, 0) date2=datetime.datetime(2023, 9, 25, 12, 0, 0, 0) date3=datetime.datetime(2023, 9, 25, 12, 1, 0, 0)

In [32]: datetime.datetime.strftime(date1, format_date)
Out[32]: '2023-09-25 11:59 AM'
In [33]: datetime.datetime.strftime(date2, format_date)
Out[33]: '2023-09-25 12:00 PM'
In [34]: datetime.datetime.strftime(date3, format_date)
Out[34]: '2023-09-25 12:01 PM'

TimeZone (TZ)

datetime.datetime(2023, 9, 25, 10, 0, 34, 441838, tzinfo=<UTC>)
import datetime from dateutil import tz TZ_PARIS=tz.gettz('Europe/Paris') TZ_UTC=tz.gettz('UTC') d_utc=datetime.datetime(2023, 10, 3, 1, 1, 1, 114228, tzinfo=TZ_UTC) d_paris=datetime.datetime(2023, 10, 3, 1, 1, 1, 114228, tzinfo=TZ_PARIS)

In [4]: d_utc.isoformat(timespec='minutes')
Out[4]: '2023-10-03T01:01+00:00'
In [5]: d_paris.isoformat(timespec='minutes')
Out[5]: '2023-10-03T01:01+02:00'

Epoch time

def get_epoch_ms(): return int(time.time() * 1000.0)

Temps

Mesure du temps d'exécution

Exemple 1

print(f"started at {time.strftime('%X')}") plop() print(f"finished at {time.strftime('%X')}")

Exemple 2

start = time.time() asyncio.run(main()) end = time.time() - start print('Total time: %.2f' % end)