How to get current time in python and break up into year, month, day, hour, minute?

后端 未结 11 1042
故里飘歌
故里飘歌 2020-11-28 01:18

I would like to get the current time in Python and assign them into variables like year, month, day, hour, minute

11条回答
  •  一整个雨季
    2020-11-28 02:08

    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.

提交回复
热议问题