从python变量获取年,月和日

时间:2019-03-12 03:09:26

标签: python python-3.x date variables

我想按年,月和日来中断变量。这是我得到的:

import datetime
from datetime import date, timedelta
yesterday = date.today() - timedelta(1)
print (yesterday)
year = datetime.date.yesterday.year
month = datetime.date.yesterday.month
day=datetime.date.yesterday.day
print (year)
print (month)
print (day)

我收到一个错误消息,说datetime.date没有属性。我对python完全不了解,感到很困惑,不胜感激

4 个答案:

答案 0 :(得分:2)

你很近

import datetime
from datetime import date, timedelta
yesterday = date.today() - timedelta(1)
print (yesterday)
year = yesterday.year
month = yesterday.month
day=yesterday.day
print (year)
print (month)
print (day)

结果是

2019-03-10

2019

3

10

答案 1 :(得分:2)

您还可以像这样简化导入语句:

from datetime import datetime, timedelta

yesterday = datetime.today() - timedelta(1)

print(yesterday)

year = yesterday.year
month = yesterday.month
day = yesterday.day

print(year)
print(month)
print(day)

您将获得输出:

2019-03-10 21:19:36.695577
2019
3
10

答案 2 :(得分:0)

当天

import datetime

current_datetime=datetime.datetime.now()
print("current_year:{}".format(current_datetime.year))
print("current_month:{}".format(current_datetime.month))
print("current_day:{}".format(current_datetime.day))

答案 3 :(得分:0)

您可以使用strftime方法

一个简单的例子:

>>> from datetime import datetime
>>> now = datetime.utcnow()
>>> year_month_day_format = '%Y-%m-%d'
>>> now.strftime(year_month_day_format)
'2020-11-06'
>>> hour_minute_format = '%H:%M'
>>> now.strftime(hour_minute_format)
'22:54'

跳跃,对别人有帮助