最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

[已解决]Python中判断datetime是否是当天

Python crifan 8023浏览 0评论

折腾:

[已解决]Flask中对于SQLAlachemy中检索特定时间内的条目

期间,需要去判断datetime是否是当天

python datetime today check

python – How can I check if a date is the same day as datetime.today()? – Stack Overflow

此处,python中,是可以用:

yourdatetime.date() == datetime.today().date()

去判断是非是当天的

不过,我此处是,对于Flask中SQLAlchemy中,通过query的filter,无法传入表达式,即无法用:

datetime.date()去判断的

所以只能换用这种方式:

    dateFormat = “%Y-%m-%d”
    timeFormat = “%H:%M:%S”
    datetimeFormat = dateFormat + ” ” + timeFormat
    app.logger.debug(‘dateFormat=%s, timeFormat=%s, datetimeFormat=%s’, dateFormat, timeFormat, datetimeFormat)
    todayDatetime = datetime.today()
    todayDate = date.today()
    #todayDateStr = todayDatetime.strftime(dateFormat)
    todayDateStr = todayDate.strftime(dateFormat)
    app.logger.debug(‘todayDate=%s, todayDateStr=%s’, todayDate, todayDateStr)
    todayStartStr = todayDateStr + ” 00:00:00″
    todayEndStr = todayDateStr + ” 23:59:59″
    app.logger.debug(‘todayStartStr=%s, todayEndStr=%s’, todayStartStr, todayEndStr)
    todayStart = datetime.strptime(todayStartStr, datetimeFormat)
    todayEnd   = datetime.strptime(todayEndStr, datetimeFormat)
    app.logger.debug(‘todayStart=%s, todayEnd=%s’, todayStart, todayEnd)
    todayEventList = Event.query.filter(and_(Event.user_openid == curUser.openid, Event.start_date >= todayStart, Event.start_date <= todayEnd)).all()
    app.logger.debug(“todayEventList=%s”, todayEventList)

去判断这个日期时间,属于当前的时间范围内,从而判断是当天的。

对应的输出是:

dateFormat=%Y-%m-%d, timeFormat=%H:%M:%S, datetimeFormat=%Y-%m-%d %H:%M:%S

<div–<——————————————————————————

<div–<——————————————————————————

DEBUG in views [/root/html/SIPEvents/sipevents/views.py:385]:
todayDate=2016-08-29, todayDateStr=2016-08-29

<div–<——————————————————————————

<div–<——————————————————————————

DEBUG in views [/root/html/SIPEvents/sipevents/views.py:388]:
todayStartStr=2016-08-29 00:00:00, todayEndStr=2016-08-29 23:59:59

<div–<——————————————————————————

<div–<——————————————————————————

DEBUG in views [/root/html/SIPEvents/sipevents/views.py:391]:
todayStart=2016-08-29 00:00:00, todayEnd=2016-08-29 23:59:59

<div–<——————————————————————————

<div–<——————————————————————————

DEBUG in views [/root/html/SIPEvents/sipevents/views.py:399]:
todayEventList=[<Event id=5 user_openid=oswjmv4X0cCXcfkIwjoDfCkeTVVY title=u’\u4eca\u5929\u505a\u5f00\u53d1′>]

参考:

python – How can I check if a date is the same day as datetime.today()? – Stack Overflow

  • date:包含年,月,日的属性
  • time:包含时,分,秒,以及时区
  • datetime:合并了date和time。有date()和time()可以获得对应的date和time的类型变量,且也有一个combine,可以把一个date和time合并为datetime。

1.比较是否是今天

yourdatetime.date() == datetime.today().date()

转载请注明:在路上 » [已解决]Python中判断datetime是否是当天

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
82 queries in 0.184 seconds, using 22.04MB memory