use*_*486 254 python time datetime python-2.7
我想获得当前时间在Python,并将它们分配到像变量year
,month
,day
,hour
,minute
.如何在Python 2.7中完成?
tza*_*man 456
该datetime
模块是你的朋友:
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
Run Code Online (Sandbox Code Playgroud)
您不需要单独的变量,返回datetime
对象上的属性就可以满足您的所有要求.
vos*_*n77 27
datetime
上面的答案更清晰,但你可以使用原始的python time
模块:
import time
strings = time.strftime("%Y,%m,%d,%H,%M,%S")
t = strings.split(',')
numbers = [ int(x) for x in t ]
print numbers
Run Code Online (Sandbox Code Playgroud)
输出:
[2016, 3, 11, 8, 29, 47]
Run Code Online (Sandbox Code Playgroud)
rig*_*sby 25
这是一个单线程,最高可达80 char线.
import time
year, month, day, hour, min = map(int, time.strftime("%Y %m %d %H %M").split())
Run Code Online (Sandbox Code Playgroud)
sky*_*489 14
通过解压缩timetuple
datetime对象,您应该得到您想要的:
from datetime import datetime
n = datetime.now()
t = n.timetuple()
y, m, d, h, min, sec, wd, yd, i = t
Run Code Online (Sandbox Code Playgroud)
对于python 3
import datetime
now = datetime.datetime.now()
print(now.year, now.month, now.day, now.hour, now.minute, now.second)
Run Code Online (Sandbox Code Playgroud)
您可以使用 gmtime
from time import gmtime
detailed_time = gmtime()
#returns a struct_time object for current time
year = detailed_time.tm_year
month = detailed_time.tm_mon
day = detailed_time.tm_mday
hour = detailed_time.tm_hour
minute = detailed_time.tm_min
Run Code Online (Sandbox Code Playgroud)
注意:可以将时间戳传递给 gmtime,默认为 time() 返回的当前时间
eg.
gmtime(1521174681)
Run Code Online (Sandbox Code Playgroud)
让我们看看如何从当前时间获取并打印python中的日,月,年:
import datetime
now = datetime.datetime.now()
year = '{:02d}'.format(now.year)
month = '{:02d}'.format(now.month)
day = '{:02d}'.format(now.day)
hour = '{:02d}'.format(now.hour)
minute = '{:02d}'.format(now.minute)
day_month_year = '{}-{}-{}'.format(year, month, day)
print('day_month_year: ' + day_month_year)
Run Code Online (Sandbox Code Playgroud)
结果:
day_month_year: 2019-03-26
Run Code Online (Sandbox Code Playgroud)