日期大小比较令解决{strftime('%Y年%m月%d日')}出错问题

大小比较代码:

 1 import datetime
 2 import time
 3 #将日期字符串转为时间再比较,time,datetime,str
 4 def valid_date(timestr):
 5     #获取当前时间日期
 6     nowTime_str = datetime.datetime.now().strftime('%Y-%m-%d') 
 7     print(nowTime_str)
 8     #mktime参数为struc_time,将日期转化为秒,
 9     e_time = time.mktime(time.strptime(nowTime_str,"%Y-%m-%d"))
10     print(e_time)
11     try:
12         s_time = time.mktime(time.strptime(timestr, '%Y-%m-%d'))
13         print(s_time)
14         #日期转化为int比较
15         diff = int(s_time)-int(e_time)
16         print(diff)
17         if diff >= 0:
18             return 1
19         else:
20             print('所查日期不能小于当前时间!!!')
21             return 0
22     except Exception as e:
23         print(e)
24         return 0
25 if __name__=='__main__':
26     valid_date("2018-10-07")

解决报错方案:

1 Traceback (most recent call last):
2   File "E:/pycharm/WorkPlace/Graduation_project/Util/有用插件/日期比较.py", line 32, in <module>
3     nowTime_str = datetime.datetime.now().strftime('%Y年%m月%d日')
4 UnicodeEncodeError: 'locale' codec can't encode character '\u5e74' in position 2: encoding error

更改为:

1 time.strftime('%Y{y}%m{m}%d{d} %H{h}%M{f}%S{s}').format(y='',m='',d='',h='',f='',s='')

 

posted @ 2021-02-21 10:46  博二爷  阅读(1050)  评论(0编辑  收藏  举报