【问题标题】:how to set default hour for my django datetimefield如何为我的 django datetimefield 设置默认小时
【发布时间】:2021-09-25 13:12:10
【问题描述】:

我试图将默认时间设置为我的 django 日期时间字段,我在我的输入中使用datetime-local,但它显示当前时间,我想将默认时间设置为下午 12:00 并且可以更改 我试过了,但没有用

from datetime import datetime

def set_default_time_checkout():
    now = datetime.now()
    new_time = now.replace(hour=12, minute=0, second=0, microsecond=0)
    return new_time

class Booking(models.Model):
    check_in = models.DateTimeField(default=timezone.now)
    check_out = models.DateTimeField(default=set_default_time_checkout,blank=True,null=True)

但不起作用 这是我的forms.py

class BookingForm(forms.ModelForm):
    check_in = forms.DateTimeField(required=True,input_formats=['%Y-%m-%dT%H:%M','%Y-%m-%dT%H:M%Z'],widget=forms.DateTimeInput(attrs={'type':'datetime-local'}))
    check_out = forms.DateTimeField(initial=set_default_time_checkout, required=False,input_formats=['%Y-%m-%dT%H:%M','%Y-%m-%dT%H:M%Z'],widget=forms.DateTimeInput(attrs={'type':'datetime-local'}))

modelform 的初始时间也不起作用,请问有可能吗?如何实现呢?我从问题中尝试了这些解决方案,但它们都不起作用 Can I set a specific default time for a Django datetime field? 提前致谢

【问题讨论】:

    标签: django python-datetime


    【解决方案1】:

    这可能有效:

    import datetime
    
    defualt=datetime.time(12, 0, 0)
    

    datetime.time() 的输出有小时、分钟和秒实例

    【讨论】:

    • 谢谢,但它不起作用,我在输入中使用了 datepicker-local,它仍然从当前时间开始
    猜你喜欢
    • 1970-01-01
    • 2021-06-23
    • 1970-01-01
    • 2017-12-29
    • 2022-08-14
    • 1970-01-01
    • 1970-01-01
    • 2018-07-21
    • 2011-04-10
    相关资源
    最近更新 更多