如何在Python中找到n天前的日期? [英] How to find the date n days ago in Python?

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

问题描述

晚上好,

我想写一个脚本,给我python几天的时间(我们叫d),它给我日期我们是d天前。

I would like to write a script where I give python a number of days (let s call it d) and it gives me the date we were d days ago.

我正在为模块日期时间苦苦挣扎:

I am struggling with the module datetime:

import datetime 

tod = datetime.datetime.now()
d = timedelta(days = 50) 
a = tod - h 
Type Error : unsupported operand type for - : "datetime.timedelta" and 
"datetime.datetime" 

感谢您的帮助

推荐答案

您已将变量与变量混合在一起,可以减去timedelta d from datetime.datetime.now()没有问题:

You have mixed something up with your variables, you can subtract timedelta d from datetime.datetime.now() with no issue:

import datetime 
tod = datetime.datetime.now()
d = datetime.timedelta(days = 50)
a = tod - d
print(a)
2014-12-13 22:45:01.743172

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

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