• Mémo Manipuler les dates en Python

  • Manipulate datetime in Python

Pour transformer une string en objet datetime :

from datetime import datetime

date = datetime.now()
date_string = str(date)

time = datetime.strptime(date_string, '%Y-%m-%d %H:%M:%S.%f')
print("Type: {}\nTime: {}\n".format(type(time), time))

A l'inverse, pour transformer un objet datetime en string.

from datetime import datetime

now = datetime.now()
date = now.strftime('%Y-%m-%d %H:%M:%S')
print("Type: {}\nDate: {}".format(type(date), date))

En sortie :

Type: <class 'datetime.datetime'>
Time: 2019-06-16 21:24:25.895983

Type: <class 'str'>
Date: 2019-06-16 21:24:25

Quelques fonctions utiles :

from datetime import datetime, timedelta


def convert_timestamp_to_date_time(timestamp: float) -> datetime:
    result = datetime.fromtimestamp(timestamp)
    return result


def convert_datetime_to_string(date_obj: datetime) -> str:
    result = date_obj.strftime("%Y-%m-%d %H:%M:%S")
    return result


def convert_string_to_datetime(date_string: str) -> datetime:
    result = datetime.strptime(date_string, "%Y-%m-%d %H:%M:%S")
    return result


def convert_timestamp(timestamp: float) -> str:
    date_string = convert_timestamp_to_date_time(timestamp=timestamp)
    return convert_datetime_to_string(date_obj=date_string)


def get_timedelta(detected: datetime, closed: datetime) -> timedelta:
    result = closed - detected
    return result


def convert_timedelta_to_string(duration: float):
    minutes, seconds = divmod(duration, 60)
    hours, minutes = divmod(minutes, 60)
    return "%02d:%02d:%02d" % (hours, minutes, seconds)


16 juin 2019 21:25