56

From what I gather, here (for example), this should print the current year in two digits

print (datetime.strftime("%y"))

However, I get this error

TypeError: descriptor 'strftime' requires a 'datetime.date' object but received a 'str'

So I tried to this

print (datetime.strftime(datetime.date()))

to get

TypeError: descriptor 'date' of 'datetime.datetime' object needs an argument

so I placed "%y" inside of thr date() above to get

TypeError: descriptor 'date' requires a 'datetime.datetime' object but received a 'str'

Which start to seem really loopy and fishy to me.

What am I missing?

0

5 Answers 5

91
import datetime
now = datetime.datetime.now()

print(now.year)

The above code works perfectly fine for me.

Sign up to request clarification or add additional context in comments.

Comments

29

The following seems to work:

import datetime
print (datetime.datetime.now().strftime("%y"))

The datetime.data object that it wants is on the "left" of the dot rather than the right. You need an instance of the datetime to call the method on, which you get through now()

Comments

12

I use this which is standard for every time

import datetime
now = datetime.datetime.now()
print ("Current date and time : ")
print (now.strftime("%Y-%m-%d %H:%M:%S"))

Comments

9

The built-in datetime module contains many functions for getting the specific time and date:

from datetime import datetime
from math import floor

now = datetime.now()

year = now.year
month = now.month
day = now.day

hour = now.hour
minute = now.minute
second = now.second
millisecond = floor(datetime.now().microsecond / 1000)
microsecond = now.microsecond

date = now.strftime("%Y-%m-%d")

time24Hour = now.strftime("%H:%M:%S")
time12Hour = now.strftime("%I:%M:%S %p")

1 Comment

A really handy function. May I suggest you include the 'Argument / Meaning / Example output' information in the code as comments so the function and notes can all be copied as a block?
6

I always use this code, which print the year to second in a tuple

import datetime

now = datetime.datetime.now()

time_now = (now.year, now.month, now.day, now.hour, now.minute, now.second)

print(time_now)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.