I would like to get the current time in Python and assign them into variables like year
, month
, day
, hour
, minute
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.
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
import time
year = time.strftime("%Y") # or "%y"
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]
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