[英]Extracting year, month, day, hour and minute from the current datetime
I need to extract year, month, day, hour and possible also minutes from the current datetime:我需要从当前日期时间中提取年、月、日、小时和可能的分钟:
import datetime
from datetime import datetime
now = datetime.now()
date_t = now.strftime("%d/%m/%Y %H:%M")
trying试
date_t.day()
date_t.month()
date_t.year()
date_t.hour()
date_t.minute()
It does not work as I have an error: AttributeError: 'str' object has no attribute 'year'
.它不起作用,因为我有一个错误:
AttributeError: 'str' object has no attribute 'year'
。 I hope you can help我希望你能帮忙
Try尝试
now.day
now.month
now.year
now.hour
now.minute
your date_t
is a String where you've formatted the date.您的
date_t
是您格式化日期的字符串。 now
is a date time
object now
是date time
object
DateTime uses certain formatting. DateTime 使用某些格式。 %d means day, %m means months.
%d 表示日,%m 表示月。 %Y means year.
%Y 表示年份。 So on and so forth!
等等等等!
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
This is not the prettiest formatting, but it works.这不是最漂亮的格式,但它有效。 You can just use:
你可以使用:
import datetime
from datetime import datetime
now = datetime.now()
print(now.hour) # 'hour' can be changed to what you need.
In response to an error you're explaining in comments below:为了响应您在下面的评论中解释的错误:
from datetime import datetime
means you do not have to do 'datetime.datetime'意味着你不必做'datetime.datetime'
Just use now
. now
就用。 And no parenths.而且没有父母。
from datetime import datetime
now = datetime.now()
print(now.day)
print(now.month)
print(now.year)
print(now.hour)
print(now.minute)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.