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

后端 未结 11 962
故里飘歌
故里飘歌 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:10

    The datetime module is your friend:

    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
    

    You don't need separate variables, the attributes on the returned datetime object have all you need.

    0 讨论(0)
  • 2020-11-28 02:17

    By unpacking timetuple of datetime object, you should get what you want:

    from datetime import datetime
    
    n = datetime.now()
    t = n.timetuple()
    y, m, d, h, min, sec, wd, yd, i = t
    
    0 讨论(0)
  • 2020-11-28 02:19
    import time
    year = time.strftime("%Y") # or "%y"
    
    0 讨论(0)
  • 2020-11-28 02:21

    Three libraries for accessing and manipulating dates and times, namely datetime, arrow and pendulum, all make these items available in namedtuples whose elements are accessible either by name or index. Moreover, the items are accessible in precisely the same way. (I suppose if I were more intelligent I wouldn't be surprised.)

    >>> 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]
    
    0 讨论(0)
  • 2020-11-28 02:22

    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
    
    0 讨论(0)
提交回复
热议问题