Python datetime - setting fixed hour and minute after using strptime to get day,month,year

前端 未结 3 465
后悔当初
后悔当初 2020-12-12 15:35

I\'ve successfully converted something of 26 Sep 2012 format to 26-09-2012 using:

datetime.strptime(request.POST[\'sample_date\'],\'%

相关标签:
3条回答
  • 2020-12-12 15:44

    If you have date as a datetime.datetime (or a datetime.date) instance and want to combine it via a time from a datetime.time instance, then you can use the classmethod datetime.datetime.combine:

    import datetime
    dt = datetime.datetime(2020, 7, 1)
    t = datetime.time(12, 34)
    combined = datetime.datetime.combine(dt.date(), t)
    
    0 讨论(0)
  • 2020-12-12 15:57

    datetime.replace() will provide the best options. Also, it provides facility for replacing day, year, and month.

    Suppose we have a datetime object and date is represented as: "2017-05-04"

    >>> from datetime import datetime
    >>> date = datetime.strptime('2017-05-04',"%Y-%m-%d")
    >>> print(date)
    2017-05-04 00:00:00
    >>> date = date.replace(minute=59, hour=23, second=59, year=2018, month=6, day=1)
    >>> print(date)
    2018-06-01 23:59:59
    
    0 讨论(0)
  • 2020-12-12 15:58

    Use datetime.replace:

    from datetime import datetime
    dt = datetime.strptime('26 Sep 2012', '%d %b %Y')
    newdatetime = dt.replace(hour=11, minute=59)
    
    0 讨论(0)
提交回复
热议问题