I would like to get the current time in Python and assign them into variables like year
, month
, day
, hour
, minute>
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.