Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 412
guagay_wk Avatar asked May 06 '15 08:05

guagay_wk


People also ask

How do I get the current year and month in Python?

In Python, in order to print the current date consisting of a year, month, and day, it has a module named datetime. From the DateTime module, import date class. Create an object of the date class. Call the today( ) function of date class to fetch todays date.

How do I get current hour and minutes in Python?

To get the current time in particular, you can use the strftime() method and pass into it the string ”%H:%M:%S” representing hours, minutes, and seconds.

How do I get the current date and time separately in Python?

Use isoformat() method on a datetime. now() instance to get the current date and time in the following ISO 8601 format: YYYY-MM-DDTHH:MM:SS. ffffff , if microsecond is not 0.

How do I print the current time in Python?

Datetime module comes built into Python, so there is no need to install it externally. To get both current date and time datetime. now() function of DateTime module is used. This function returns the current local date and time.


2 Answers

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.

like image 90
tzaman Avatar answered Sep 20 '22 06:09

tzaman


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()) 
like image 26
rigsby Avatar answered Sep 22 '22 06:09

rigsby