从 Python 中的日期减去 n 天 [英] Subtracting n days from date in Python

查看:70
本文介绍了从 Python 中的日期减去 n 天的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从文件的时间戳中减去 n 天,但它似乎不起作用.我已经阅读了这篇文章,我想我已经接近了.

I want to subtract n days from a file's timestamp, but it doesn't seem to be working. I have read this post, and I think I'm close.

这是我的代码的摘录:

import os, time
from datetime import datetime, timedelta

def processData1( pageFile ):
    f = open(pageFile, "r")
    page = f.read()
    filedate = time.strftime('%m/%d/%Y', time.gmtime(os.path.getmtime(pageFile)))
    print filedate
    end_date = filedate - datetime.timedelta(days=10)
    print end_date

打印 filedate 有效,因此可以从文件中正确读取日期.减法位似乎不起作用.

Printing filedate works, so that date is read correctly from the files. It's the subtraction bit that doesn't seem to be working.

所需的输出:如果 filedate 是 06/11/2013,print end_date 应该产生 06/01/2013.

Desired output: If filedate is 06/11/2013, print end_date should yield 06/01/2013.

推荐答案

当你使用 time.strftime() 您实际上是在转换 struct_time 到一个字符串.

When you use time.strftime() you are actually converting a struct_time to a string.

so filedate 实际上是一个字符串.当你尝试从它 +- 一个 datetime.timedelta 时,你会得到一个错误.示例 -

so filedate is actually a string. When you try to + or - a datetime.timedelta from it, you would get an error. Example -

In [5]: s = time.strftime('%m/%d/%Y', time.gmtime(time.time()))

In [6]: s
Out[6]: '09/01/2015'

In [8]: s - datetime.timedelta(days=10)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-8-fb1d19ed0b02> in <module>()
----> 1 s - datetime.timedelta(days=10)

TypeError: unsupported operand type(s) for -: 'str' and 'datetime.timedelta'

获得与 time.gmtime() 类似的行为 可以改为使用 datetime.datetime.utcfromtimestamp() ,这将提供一个日期时间对象,您可以从中减去时间增量.

To get a similar behavior to time.gmtime() to can instead use datetime.datetime.utcfromtimestamp() , this would provide a datetime object, from which you can subtract the timedelta.

然后如果您想要的最终结果实际上是一个字符串,您可以使用 datetime.strftime() 将其转换为所需格式的字符串.示例 -

And then if the end result you want is actually a string, you can use datetime.strftime() to convert it to string in required format. Example -

import os
from datetime import datetime, timedelta

def processData1( pageFile ):
    f = open(pageFile, "r")
    page = f.read()
    filedate = datetime.utcfromtimestamp(os.path.getmtime(pageFile)))
    print filedate
    end_date = filedate - timedelta(days=10)
    print end_date   #end_date would be a datetime object.
    end_date_string = end_date.strftime('%m/%d/%Y')
    print end_date_string

这篇关于从 Python 中的日期减去 n 天的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆