Search code examples
pythonpython-datetime

Extracting year, month, day, hour and minute from the current datetime


I need to extract year, month, day, hour and possible also minutes from the current datetime:

import datetime
from datetime import datetime
    
now = datetime.now() 
date_t = now.strftime("%d/%m/%Y %H:%M")

trying

date_t.day()
date_t.month()
date_t.year()
date_t.hour()
date_t.minute()

It does not work as I have an error: AttributeError: 'str' object has no attribute 'year'. I hope you can help


Solution

  • Just use now. And no parenths.

    from datetime import datetime
    
    now = datetime.now()
    
    print(now.day)
    print(now.month)
    print(now.year)
    print(now.hour)
    print(now.minute)