How to get current time in python and break up into year, month, day, hour, minute?
我想用Python获取当前时间,并将它们分配到
1 2 3 4 | 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 |
您不需要单独的变量,返回的
上面的
1 2 3 4 5 | import time strings = time.strftime("%Y,%m,%d,%H,%M,%S") t = strings.split(',') numbers = [ int(x) for x in t ] print numbers |
输出:
1 | [2016, 3, 11, 8, 29, 47] |
这里有一行代码刚好在80个字符的最大值下面。
1 2 | import time year, month, day, hour, minute = time.strftime("%Y,%m,%d,%H,%M").split(',') |
通过解压缩datetime对象的
1 2 3 4 5 | from datetime import datetime n = datetime.now() t = n.timetuple() y, m, d, h, min, sec, wd, yd, i = t |
python 3
1 2 3 | import datetime now = datetime.datetime.now() print(now.year, now.month, now.day, now.hour, now.minute, now.second) |
让我们看看如何获得和打印天,月,年在python从目前的时间:
1 2 3 4 5 6 7 8 9 10 11 | 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) |
结果:
1 | day_month_year: 2019-03-26 |
1 2 | import time year = time.strftime("%Y") # or"%y" |
您可以使用gmtime
1 2 3 4 5 6 7 8 9 10 | 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 |
注:时间戳可以传递给gmtime,默认为当前时间返回的时间()
1 2 | eg. gmtime(1521174681) |
看到struct_time
三个用于访问和操作日期和时间的库,即datetime、箭头和摆锤,都在namedtuple中提供这些项,这些元素可以通过名称或索引访问。此外,访问这些项目的方式也完全相同。(我想如果我更聪明一点,我就不会感到惊讶了。)
1 2 3 4 5 6 7 8 9 10 | >>> YEARS, MONTHS, DAYS, HOURS, MINUTES = range(5) >>> import datetime >>> import arrow >>> import pendulum >>> [datetime.datetime.now().timetuple()[i] for i in [YEARS, MONTHS, DAYS, HOURS, MINUTES]] [2017, 6, 16, 19, 15] >>> [arrow.now().timetuple()[i] for i in [YEARS, MONTHS, DAYS, HOURS, MINUTES]] [2017, 6, 16, 19, 15] >>> [pendulum.now().timetuple()[i] for i in [YEARS, MONTHS, DAYS, HOURS, MINUTES]] [2017, 6, 16, 19, 16] |
这是一个较老的问题,但我想出了一个我认为其他人可能会喜欢的解决方案。
1 2 3 4 5 6 7 8 9 10 11 12 13 | def get_current_datetime_as_dict(): n = datetime.now() t = n.timetuple() field_names = ["year", "month", "day", "hour", "min", "sec", "weekday", "md", "yd"] return dict(zip(field_names, t)) |
可以用另一个数组压缩timetuple(),该数组创建带标签的元组。将其转换为字典,生成的产品可以使用
这比这里的其他一些解决方案的开销要大一些,但是我发现能够在代码中访问命名值是非常好的。
可以使用datetime模块在Python 2.7中获取当前日期和时间
1 2 | import datetime print datetime.datetime.now() |
输出:
1 | 2015-05-06 14:44:14.369392 |