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

user781486 picture user781486 · May 6, 2015 · Viewed 396.9k times · Source

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?

Answer

tzaman picture tzaman · May 6, 2015

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.