如何在python中获取当前时间并分解为年、月、日、小时、分钟?

如何在python中获取当前时间并分解为年、月、日、小时、分钟?

问题描述:

我想在 Python 中获取当前时间并将它们分配给诸如 yearmonthdayhour 之类的变量分钟.这如何在 Python 2.7 中完成?

I would like to get the current time in Python and assign them into variables like year, month, day, hour, minute. How can this be done in Python 2.7?

datetime 模块是你的朋友:

The datetime module is your friend:

import datetime
now = datetime.datetime.now()
print(now.year, now.month, now.day, now.hour, now.minute, now.second)
# 2015 5 6 8 53 40

您不需要单独的变量,返回的 datetime 对象上的属性拥有您所需要的一切.

You don't need separate variables, the attributes on the returned datetime object have all you need.