【问题标题】:How to connect commands to calendar如何将命令连接到日历
【发布时间】:2015-02-23 13:34:53
【问题描述】:
 import time;

 localtime = time.asctime( time.localtime(time.time()) )
 print "Local current time :", localtime

我试图弄清楚如何添加这样的写命令: “明天。”然后将在日历中的第二天打印出来,依此类推。 我已经设法获取日历,但我需要有关如何将命令连接到它的帮助。提前致谢!

【问题讨论】:

  • 不相关:您的代码相当于 Python 中的print "Local current time:", time.ctime() 调用。

标签: python time calendar expression routed-commands


【解决方案1】:

编写一个程序来处理用户以“第二天”形式输入的一组有限的表达式并不难,但如果你想处理任意日期查询表达式,事情就会变得有点复杂。 :)

但是,如果您只想知道如何在 Python 中操作日期(和时间),则必须阅读 datetimecalendar 模块的文档。 datetime 模块相当大而且有点乱,所以不要指望立即掌握它。但是,如果您通读文档并编写大量小测试程序,您很快就会学会如何使用它。

为了帮助您入门,这里有一个小示例,说明如何从给定日期添加或减去任意天数。该程序使用strftime 方法来显示日期,您可能已经在time 模块文档中看到过。

#!/usr/bin/env python

import datetime

def date_string(date):
    return date.strftime('%A %d %B %Y')

oneday = datetime.timedelta(days=1)    

today = datetime.date.today()
print today

print 'Today is', date_string(today)
print 'Tomorrow is', date_string(today + oneday)
print 'Yesterday was', date_string(today - oneday)
print 'In one week it will be', date_string(today + oneday * 7)

输出

2015-02-24
Today is Tuesday 24 February 2015
Tomorrow is Wednesday 25 February 2015
Yesterday was Monday 23 February 2015
In one week it will be Tuesday 03 March 2015

【讨论】:

  • next_day = date.today() + timedelta(days=1) 在我看来并不复杂。一般来说,它可能与now+24h 不同。另外,请注意:datetimecalendar 实现“预测公历”日历。人们可能会使用其他日历,例如用于宗教目的:PyICU 包在这种情况下可能很有用。
  • @J.F.Sebastian:好点;使用当地时间可以在夏令时转换周围做坏事。但我已经告诉my favourite anecdote 上次我们讨论时间问题。
  • 注意:DST 并不是 UTC 偏移量可能改变的唯一原因。忘记错误的时间,错误的时区处理可能会导致错误的日期!我记得读过一则轶事,其中飞行员死亡是因为有人没有在软件中正确处理国际日期变更线——消息来源不可信,但我可以很容易地想象出这样的错误是如何产生的。这是another anecdote (everybody is alive)
猜你喜欢
  • 1970-01-01
  • 2015-01-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-06
  • 1970-01-01
  • 1970-01-01
  • 2021-01-21
相关资源
最近更新 更多