Convert date to datetime in Python

后端 未结 10 2391
感动是毒
感动是毒 2020-11-28 17:10

Is there a built-in method for converting a date to a datetime in Python, for example getting the datetime for the midnight of the giv

10条回答
  •  一整个雨季
    2020-11-28 17:44

    Do I really have to manually call datetime(d.year, d.month, d.day)

    No, you'd rather like to call

    date_to_datetime(dt)
    

    which you can implement once in some utils/time.py in your project:

    from typing import Optional
    from datetime import date, datetime
    
    def date_to_datetime(
        dt: date,
        hour: Optional[int] = 0,
        minute: Optional[int] = 0, 
        second: Optional[int] = 0) -> datetime:
    
        return datetime(dt.year, dt.month, dt.day, hour, minute, second)
    

提交回复
热议问题