我是python的初学者,我有来自shell脚本的这个日期和时间代码,我如何将它变成python,我怎么能从上个月到现在才开始使用
ToDay=`date "+%Y%m%d"`
CheckDATE=`date "+%Y-%m-%d" --date '1 day ago'`
NOWDATE=`date "+%Y-%m-%d"`
这是python代码
from datetime import datetime, date, timedelta
progToRun = 'python ' + ScriptDir + '/bin/panafapi.py -K ' + secretkey + ' --samples -j -r "{\\"query\\":{\\"operator\\":\\"all\\",\\"children\\":[{\\"field\\":\\"alias.ip_address\\",\\"operator\\":\\"contains\\",\\"value\\":\\"' + ResultFile + '\\"},{\\"operator\\":\\"any\\",\\"children\\":[{\\"field\\":\\"sample.update_date\\",\\"operator\\":\\"is in the range\\",\\"value\\":[\\"' + CheckDATE + 'T00:00:00\\",\\"' + NOWDATE + 'T23:59:59\\"]},{\\"field\\":\\"sample.create_date\\",\\"operator\\":\\"is in the range\\",\\"value\\":[\\"' + CheckDATE + 'T00:00:00\\",\\"' + NOWDATE + 'T23:59:59\\"]},{\\"operator\\":\\"any\\",\\"children\\":[{\\"field\\":\\"sample.malware\\",\\"operator\\":\\"is\\",\\"value\\":1},{\\"field\\":\\"sample.malware\\",\\"operator\\":\\"is\\",\\"value\\":4}]}]}]},\\"scope\\":\\"global\\",\\"size\\":1,\\"from\\":0,\\"sort\\":{\\"create_date\\":{\\"order\\":\\"desc\\"}}}" > ' + ResultDir + 'srciplist-' + ToDay + '.json'
ToDay = datetime.now().strftime('%Y%m%d')
CheckDATE = datetime.strptime("2017-12-01", "%Y-%m-%d").date()
NOWDATE = datetime.now().date()
错误:
progToRun = 'python ' + ScriptDir + '/bin/panafapi.py -K ' + secretkey + ' --samples -j -r "{\\"query\\":{\\"operator\\":\\"all\\",\\"children\\":[{\\"field\\":\\"alias.ip_address\\",\\"operator\\":\\"contains\\",\\"value\\":\\"' + ResultFile + '\\"},{\\"operator\\":\\"any\\",\\"children\\":[{\\"field\\":\\"sample.update_date\\",\\"operator\\":\\"is in the range\\",\\"value\\":[\\"' + CheckDATE + 'T00:00:00\\",\\"' + NOWDATE + 'T23:59:59\\"]},{\\"field\\":\\"sample.create_date\\",\\"operator\\":\\"is in the range\\",\\"value\\":[\\"' + CheckDATE + 'T00:00:00\\",\\"' + NOWDATE + 'T23:59:59\\"]},{\\"operator\\":\\"any\\",\\"children\\":[{\\"field\\":\\"sample.malware\\",\\"operator\\":\\"is\\",\\"value\\":1},{\\"field\\":\\"sample.malware\\",\\"operator\\":\\"is\\",\\"value\\":4}]}]}]},\\"scope\\":\\"global\\",\\"size\\":1,\\"from\\":0,\\"sort\\":{\\"create_date\\":{\\"order\\":\\"desc\\"}}}" > ' + ResultDir + 'srciplist-' + ToDay + '.json'
TypeError: must be str, not datetime.date
答案 0 :(得分:0)
您可以使用以下代码转换日期:
CheckDATE = datetime.datetime.strptime("2017-12-01", "%Y-%m-%d").date()
ToDAY = datetime.datetime.now().strftime("%Y-%m-%d")
CheckDATE = CheckDATE.strftime("%Y-%m-%d")
最后添加日期仅输出日期部分并省略时间。 我希望这能回答你的问题。
编辑:根据其他信息更新。
答案 1 :(得分:0)
>>> import datetime
>>> today = datetime.date.today()
>>> yesterday = today - datetime.timedelta(days=1)
>>> ToDay = today.strftime("%Y%m%d")
>>> CheckDATE = yesterday.strftime("%Y-%m-%d")
>>> NOWDATE = today.strftime("%Y-%m-%d")
>>> print ToDay
20180126
>>> print CheckDATE
2018-01-25
>>> print NOWDATE
2018-01-26