Convert date to datetime in Python

后端 未结 10 2381
感动是毒
感动是毒 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

    You can use datetime.combine(date, time); for the time, you create a datetime.time object initialized to midnight.

    from datetime import date
    from datetime import datetime
    
    dt = datetime.combine(date.today(), datetime.min.time())
    
    0 讨论(0)
  • 2020-11-28 17:44

    You can use the date.timetuple() method and unpack operator *.

    args = d.timetuple()[:6]
    datetime.datetime(*args)
    
    0 讨论(0)
  • 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)
    
    0 讨论(0)
  • 2020-11-28 17:45

    You can use easy_date to make it easy:

    import date_converter
    my_datetime = date_converter.date_to_datetime(my_date)
    
    0 讨论(0)
  • 2020-11-28 17:52

    If you need something quick, datetime_object.date() gives you a date of a datetime object.

    0 讨论(0)
  • 2020-11-28 17:53

    I am a newbie to Python. But this code worked for me which converts the specified input I provide to datetime. Here's the code. Correct me if I'm wrong.

    import sys
    from datetime import datetime
    from time import mktime, strptime
    
    user_date = '02/15/1989'
    if user_date is not None:
         user_date = datetime.strptime(user_date,"%m/%d/%Y")
    else:
         user_date = datetime.now()
    print user_date
    
    0 讨论(0)
提交回复
热议问题