How to get current time in python and break up into year, month, day, hour, minute?
514,204
Solution 1
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.
Solution 2
Here's a one-liner that comes in just under the 80 char line max.
import time
year, month, day, hour, min = map(int, time.strftime("%Y %m %d %H %M").split())
Solution 3
The datetime
answer by tzaman 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]
Solution 4
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
Solution 5
Let's see how to get and print day,month,year in python from current time:
import datetime
now = datetime.datetime.now()
year = '{:02d}'.format(now.year)
month = '{:02d}'.format(now.month)
day = '{:02d}'.format(now.day)
hour = '{:02d}'.format(now.hour)
minute = '{:02d}'.format(now.minute)
day_month_year = '{}-{}-{}'.format(year, month, day)
print('day_month_year: ' + day_month_year)
result:
day_month_year: 2019-03-26
Author by
guagay_wk
Updated on September 13, 2020Comments
-
guagay_wk over 3 years
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? -
Sean.H almost 5 yearsjust a suplyment:
import time \n now=time.localtime() \n print now.tm_year, now.tm_mon, now.tm_mday, now.tm_hour, now.tm_hour, now.tm_min, now.tm_sec, now.tm_wday, now.tm_yday, now.tm_isdst
-
Armster almost 4 yearsHeads up: you are shadowing the builtin function "min"