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?
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.
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.
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.
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.
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.
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())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With