在 python 配置文件中存储要跳过的日期
Storing dates to skip in python config file
在我的配置中我有
SKIP_DATES = ['2016-02-11', '2016-02-13']
然后在我的脚本中我有
if dt.date() in config.SKIP_DATES:
print "Skipping date: {0}".format(dt.date())
continue
但这行不通,因为 dt.date 是一个 datetime.date 对象,而 config.SKIP_DATES 是 'string dates'.
的列表
我怎样才能轻松解决这个问题?
谁能为这个 post 推荐一个更好的名字?
您可以将 dt
日期时间对象更改为字符串:
from datetime import datetime
date_object = datetime(2016, 2, 11)
print(date_object.strftime("%Y-%m-%d")) % prints string: 2016-02-11
然后检查它是否在日期字符串数组中。或者反着做。
您的日期格式似乎与 date.isoformat()
:
date.isoformat()
Return a string representing the date in ISO 8601 format, ‘YYYY-MM-DD’.
For example, date(2002, 12, 4).isoformat() == '2002-12-04'.
所以你可以这样做:
if dt.date().isoformat() in config.SKIP_DATES:
print "Skipping date: {0}".format(dt.date())
continue
注意datetime.date
的字符串表示使用相同的函数:
date.__str__()
For a date d, str(d) is equivalent to d.isoformat().
这就是为什么 print dt.date()
给出像 '2016-10-31'
这样的输出的原因。当然,您可以使用集合而不是列表来存储您的跳过日期。
在我的配置中我有
SKIP_DATES = ['2016-02-11', '2016-02-13']
然后在我的脚本中我有
if dt.date() in config.SKIP_DATES:
print "Skipping date: {0}".format(dt.date())
continue
但这行不通,因为 dt.date 是一个 datetime.date 对象,而 config.SKIP_DATES 是 'string dates'.
的列表我怎样才能轻松解决这个问题?
谁能为这个 post 推荐一个更好的名字?
您可以将 dt
日期时间对象更改为字符串:
from datetime import datetime
date_object = datetime(2016, 2, 11)
print(date_object.strftime("%Y-%m-%d")) % prints string: 2016-02-11
然后检查它是否在日期字符串数组中。或者反着做。
您的日期格式似乎与 date.isoformat()
:
date.isoformat()
Return a string representing the date in ISO 8601 format, ‘YYYY-MM-DD’.
For example, date(2002, 12, 4).isoformat() == '2002-12-04'.
所以你可以这样做:
if dt.date().isoformat() in config.SKIP_DATES:
print "Skipping date: {0}".format(dt.date())
continue
注意datetime.date
的字符串表示使用相同的函数:
date.__str__()
For a date d, str(d) is equivalent to d.isoformat().
这就是为什么 print dt.date()
给出像 '2016-10-31'
这样的输出的原因。当然,您可以使用集合而不是列表来存储您的跳过日期。