0

I'll ask the question using an example code I'm stuck with. I have two questions but they sort of ask the same concept. I'm trying to print date/time using:

print(datetime.now().day, datetime.now().month, datetime.now().hour, datetime.now().minute)

QUESTION 1: But I don't want to keep retyping datetime.now() all the time. Is there a way to do this in Python?

Something like this??

print("{day} - {month} - {hour}:{minute}".format(datetiem.now())

Obviously that's wrong but you get the idea.

QUESTION 2: Or, is there a way to automate module call from a class like this:

for item in ['day', 'month', 'hour', 'minute']:
    print(datetime.now().item)

Thanks.

4 Answers4

1

if you just want to format a datetime, you can do one of those:

from datetime import datetime

dt = datetime.now()

print("{0.day} - {0.month} - {0.hour}:{0.minute}".format(dt)) # 25 - 4 - 16:49
print('{:%d - %m - %H:%M}'.format(dt))                        # 25 - 04 - 16:49

the second one uses the format mini-language with the format specifiers for datetime.

to get attributes dynamically, use getattr:

for item in ['day', 'month', 'hour', 'minute']:
    print(getattr(dt, item))
hiro protagonist
  • 44,693
  • 14
  • 86
  • 111
0

Regarding Q1, you could do something like

now = datetime.now()
print(now.day, now.month, now.hour, now.minute)
couragewolf
  • 111
  • 2
  • 9
0

You mean this ?

datetime.now().strftime("%Y-%m-%d %M:%H:%S")
gushitong
  • 1,898
  • 16
  • 24
0

Take a look here for a similar question someone asked. There is an example where they use str.format() like how you would like to.

print "We are the {:%d, %b %Y}".format(today)

For the other datetime directives, here is the documentation for it.

Edit for Clarification

As mentioned in the article above, strftime() and format() will work the same now as of PEP3101.

Community
  • 1
  • 1
cmpgamer
  • 352
  • 1
  • 7