时间相关
class TT(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=256, blank=True, null=True) shijian = models.DateField(auto_now=True,blank=True) # 最后修改时间,每次自动更新 chuangjianshijian = models.DateTimeField(auto_now_add=True,blank=True) # 不可修改时间,第一次创建时间 jisuanshijian = models.DateField(blank=True,null=True)
from django.core import serializers import datetime def tt(request): data = request.GET data = dict(data) print(data) real_dict = {} for k, v in data.items(): real_dict[k] = v[0] name = real_dict["name"] a = datetime.date.today() b = a + datetime.timedelta(weeks=1) TT.objects.create(name=name, jisuanshijian=b) # obj = TT.objects.all() ret = serializers.serialize("json", obj) # return HttpResponse("ok") return HttpResponse(ret)
from django.test import TestCase # Create your tests here. # import datetime from datetime import datetime,timedelta,date a = datetime.strptime('2018-03-02 17:41:20', '%Y-%m-%d %H:%M:%S') print(type(a)) print(a) """ <class 'datetime.datetime'> 2018-03-02 17:41:20 """ a = datetime.strptime('2018-03-02 17:41:20', '%Y-%m-%d %H:%M:%S') b = a + timedelta(weeks=1) print(type(b)) print(b) """ <class 'datetime.datetime'> 2018-03-09 17:41:20 """ a = date.today().isoformat() print(type(a)) print(a) """ <class 'str'> 2019-11-26 """ a = date.today() print(type(a)) print(a) """ <class 'datetime.date'> 2019-11-26 """ a = date.today() b = a + timedelta(weeks=1) print(type(b)) print(b) """ <class 'datetime.date'> 2019-12-03 """ # import time # a = time.strftime('%Y-%m-%d',time.localtime(time.time())) # print(type(a)) # print(a) """ <class 'str'> 2019-11-26 """ str = '2012-11-19' date_time = datetime.strptime(str,'%Y-%m-%d') print(type(date_time)) print(date_time) """ <class 'datetime.datetime'> 2012-11-19 00:00:00 """
import datetime str = '2012-11-19' datetime_date = datetime.datetime.strptime(str, "%Y-%m-%d") print(type(datetime_date ), datetime_date ) date_time = datetime.datetime.date(datetime_date) print(type(date_time), date_time) """ <class 'datetime.datetime'> 2012-11-19 00:00:00 <class 'datetime.date'> 2012-11-19 """
import datetime str = '2020-11-19' a = datetime.datetime.strptime(str, "%Y-%m-%d") print(type(a), a) b = datetime.datetime.date(a) print(type(b), b) c = datetime.date.today() # if a > c: # print("a>c") # 不可以比较 if b > c: # 可以比较 print("b>c") else: print("b<c") “”“ <class 'datetime.datetime'> 2020-11-19 00:00:00 <class 'datetime.date'> 2020-11-19 b>c ”“”
date可以和DateField比较 datetime可以和DateTimeField比较 a = datetime.date.today() b = a - datetime.timedelta(weeks=1) 取出models对象,直接比较时间的字段 obj = TT.objects.filter(name="张飞").first() if a > obj.shijian: print("第一个比较") else: print("比较也算成功了") if b > obj.jisuanshijian: print("222第一个比较") else: print("2222比较也算成功了")