How to get current time in python and break up int

2019-01-12 21:33发布

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?

10条回答
Fickle 薄情
2楼-- · 2019-01-12 22:04
import time
year = time.strftime("%Y") # or "%y"
查看更多
Juvenile、少年°
3楼-- · 2019-01-12 22:07

This is an older question, but I came up with a solution I thought others might like.

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() can be zipped with another array, which creates labeled tuples. Cast that to a dictionary and the resultant product can be consumed with get_current_datetime_as_dict()['year'].

This has a little more overhead than some of the other solutions on here, but I've found it's so nice to be able to access named values for clartiy's sake in the code.

查看更多
欢心
4楼-- · 2019-01-12 22:08

The datetime answer above is much cleaner, but you can do it with the original python time module:

import time
strings = time.strftime("%Y,%m,%d,%H,%M,%S")
t = strings.split(',')
numbers = [ int(x) for x in t ]
print numbers

Output:

[2016, 3, 11, 8, 29, 47]
查看更多
倾城 Initia
5楼-- · 2019-01-12 22:09

you can use datetime module to get current Date and Time in Python 2.7

import datetime
print datetime.datetime.now()

Output :

2015-05-06 14:44:14.369392
查看更多
登录 后发表回答