Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialsidni ahmed
3,329 Pointsgetting datetime without creating variable
in this video we have made variables:
now = datetime.datetime.now() today = datetime.datetime.today()
by creating these variables we can do things like:
now.date() now.timestamp today.hour today.month
my question is that here we have made variables, but is there a way just to get the same output as 'now' and 'today' by just accessing the datetime library and not creating a variable. how would you do this? Thanks
2 Answers
Chris Freeman
Treehouse Moderator 68,441 PointsYou can access the values by using the datetime
methods directly;
# print 'now'
print(datetime.datetime.now())
# print date
print(datetime.datetime.now().date())
# print hour
print(datetime.datetime.today().hour)
# print month
print(datetime.datetime.today().month)
Richard Supak
9,614 PointsAs Chris stated above, you can access the methods directly, but remember, when you store the value in a variable, you're storing a particular value called by that method. now = datetime.datetime.now() will always return the save value as long as you don't reassign now
, whereas calling the method directly gives back the value at that time, each time.