[英]python substract months from datetime object
I would like to substract months and get a result in the form yyyymmdd. 我想减去几个月并以yyyymmdd的形式得到结果。 To start I am given a string timestamp in sec, then here is what I'm doing:
首先,给我一个以秒为单位的字符串时间戳记,然后这就是我正在做的事情:
>>> ts=1454284800
>>> billdate = datetime.datetime.strptime(time.strftime('%Y%m%d', time.gmtime(ts)), '%Y%m%d') - datetime.timedelta(5*365/12.0)
>>> billdate
datetime.datetime(2015, 9, 1, 22, 0)
>>>
In my snippet I substract 5 months, and get datetime.datetime(2015, 9, 1, 22, 0). 在我的代码段中,我减去了5个月,并得到datetime.datetime(2015,9,1,22,0)。 I would like to get rid of the the hour 22 and get datetime.datetime(2015, 9, 1, 0, 0).
我想摆脱小时22,并获取datetime.datetime(2015,9,1,0,0)。
Thanks in advance. 提前致谢。
Point 1: 22 is not day. 点1:22不是一天。 It is hours.
是几个小时。
Point 2: If you want to get rid of hours and get datetime for 12:00 AM, then try this: 要点2:如果您想摆脱时间并获取12:00 AM的日期时间,请尝试以下操作:
>>> billdate = datetime.datetime(billdate.year, billdate.month, billdate.day)
>>> billdate
datetime.datetime(2015, 9, 1, 0, 0)
If you want to modify fields of the datetime.datetime object, you need to use replace
如果要修改datetime.datetime对象的字段,则需要使用
replace
billdate = billdate.replace(hour=0)
Quote from the datetime wiki page 从datetime Wiki页面引用
datetime.replace([year[, month[, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]]]])
Return a datetime with the same attributes, except for those attributes given new values by whichever keyword arguments are specified
返回具有相同属性的日期时间,但那些通过指定关键字参数给定新值的属性除外
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.