从当前日期时间中提取年、月、日、小时和分钟
Extracting year, month, day, hour and minute from the current datetime
我需要从当前日期时间中提取年、月、日、小时和分钟数:
import datetime
from datetime import datetime
now = datetime.now()
date_t = now.strftime("%d/%m/%Y %H:%M")
正在尝试
date_t.day()
date_t.month()
date_t.year()
date_t.hour()
date_t.minute()
它不起作用,因为我有一个错误:AttributeError: 'str' object has no attribute 'year'
。
希望能帮到你
只需使用now
。没有父母。
from datetime import datetime
now = datetime.now()
print(now.day)
print(now.month)
print(now.year)
print(now.hour)
print(now.minute)
尝试
now.day
now.month
now.year
now.hour
now.minute
您的 date_t
是一个字符串,您在其中设置了日期格式。 now
是一个 date time
对象
DateTime 使用特定格式。 %d 表示天,%m 表示月。 %Y 表示年份。以此类推!
import datetime
from datetime import datetime
now = datetime.now()
date_total = now.strftime("%d/%m/%Y %H:%M")
day = now.strftime("%d")
month = now.strftime("%m")
year = now.strftime("%Y")
hour = now.strftime("%H")
minute = now.strftime("%M")
print(day) # you can change this to whatever you want now, as I've set different vairables to different date formats
这不是最漂亮的格式,但它有效。您可以只使用:
import datetime
from datetime import datetime
now = datetime.now()
print(now.hour) # 'hour' can be changed to what you need.
针对您在以下评论中解释的错误:
from datetime import datetime
意味着你不必做'datetime.datetime'
我需要从当前日期时间中提取年、月、日、小时和分钟数:
import datetime
from datetime import datetime
now = datetime.now()
date_t = now.strftime("%d/%m/%Y %H:%M")
正在尝试
date_t.day()
date_t.month()
date_t.year()
date_t.hour()
date_t.minute()
它不起作用,因为我有一个错误:AttributeError: 'str' object has no attribute 'year'
。
希望能帮到你
只需使用now
。没有父母。
from datetime import datetime
now = datetime.now()
print(now.day)
print(now.month)
print(now.year)
print(now.hour)
print(now.minute)
尝试
now.day
now.month
now.year
now.hour
now.minute
您的 date_t
是一个字符串,您在其中设置了日期格式。 now
是一个 date time
对象
DateTime 使用特定格式。 %d 表示天,%m 表示月。 %Y 表示年份。以此类推!
import datetime
from datetime import datetime
now = datetime.now()
date_total = now.strftime("%d/%m/%Y %H:%M")
day = now.strftime("%d")
month = now.strftime("%m")
year = now.strftime("%Y")
hour = now.strftime("%H")
minute = now.strftime("%M")
print(day) # you can change this to whatever you want now, as I've set different vairables to different date formats
这不是最漂亮的格式,但它有效。您可以只使用:
import datetime
from datetime import datetime
now = datetime.now()
print(now.hour) # 'hour' can be changed to what you need.
针对您在以下评论中解释的错误:
from datetime import datetime
意味着你不必做'datetime.datetime'