Python - 以 YYYY-MM-DD 格式获取昨天的日期作为字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30483977/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python - Get Yesterday's date as a string in YYYY-MM-DD format
提问by Jacob
As an input to an API request I need to get yesterday's date as a string in the format YYYY-MM-DD
. I have a working version which is:
作为 API 请求的输入,我需要获取昨天的日期作为格式的字符串YYYY-MM-DD
。我有一个工作版本,它是:
yesterday = datetime.date.fromordinal(datetime.date.today().toordinal()-1)
report_date = str(yesterday.year) + \
('-' if len(str(yesterday.month)) == 2 else '-0') + str(yesterday.month) + \
('-' if len(str(yesterday.day)) == 2 else '-0') + str(yesterday.day)
There must be a more elegant way to do this, interested for educational purposes as much as anything else!
必须有一种更优雅的方式来做到这一点,对教育目的和其他任何事情都感兴趣!
采纳答案by Kasramvd
You Just need to subtract one day from today's date. datetime.timedelta(1)
will gieve you a timedelta
objectwhich is a duration of one day and is subtractable from datetime
object. Then you can use datetime.strftime
in orer to convert the date object to string based on your espected format:
你只需要从今天的日期减去一天。datetime.timedelta(1)
会给你一个持续时间为一天的timedelta
对象,并且可以从datetime
对象中减去。然后您可以datetime.strftime
在 orer中使用根据您预期的格式将日期对象转换为字符串:
>>> from datetime import datetime, timedelta
>>> datetime.strftime(datetime.now() - timedelta(1), '%Y-%m-%d')
'2015-05-26'
Note that instead of calling the datetime.strftime
function, you can also directly use strftime
method of datetime
objects:
请注意datetime.strftime
,您也可以直接使用对象的strftime
方法,而不是调用函数datetime
:
>>> (datetime.now() - timedelta(1)).strftime('%Y-%m-%d')
'2015-05-26'
回答by Paul Rubel
>>> import datetime
>>> datetime.date.fromordinal(datetime.date.today().toordinal()-1).strftime("%F")
'2015-05-26'
回答by theRahulMody
An alternative answer that uses today()
method to calculate current date and then subtracts one using timedelta()
. Rest of the steps remain the same.
另一种答案是使用today()
method 来计算当前日期,然后使用timedelta()
. 其余步骤保持不变。
https://docs.python.org/3.7/library/datetime.html#timedelta-objects
https://docs.python.org/3.7/library/datetime.html#timedelta-objects
from datetime import date, timedelta
today = date.today()
yesterday = today - timedelta(days = 1)
print(today)
print(yesterday)
Output:
2019-06-14
2019-06-13