1

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

Safwan Samsudeen
  • 1,645
  • 1
  • 10
  • 25
LdM
  • 674
  • 7
  • 23

3 Answers3

3

Try

now.day
now.month
now.year
now.hour
now.minute

your date_t is a String where you've formatted the date. now is a date time object

Mike Cargal
  • 6,610
  • 3
  • 21
  • 27
2

DateTime uses certain formatting. %d means day, %m means months. %Y means year. So on and so forth!

import datetime
from datetime import datetime

now = datetime.now() 
date_total = now.strftime("%d/%m/%Y %H:%M")
day = now.strftime("%d")
month = now.strftime("%m")
year = now.strftime("%Y")
hour = now.strftime("%H")
minute = now.strftime("%M")
print(day) # you can change this to whatever you want now, as I've set different vairables to different date formats

This is not the prettiest formatting, but it works. You can just use:

import datetime
from datetime import datetime

now = datetime.now() 
print(now.hour) # 'hour' can be changed to what you need.

In response to an error you're explaining in comments below:

from datetime import datetime

means you do not have to do 'datetime.datetime'

StevenHarvey
  • 126
  • 5
1

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)
Safwan Samsudeen
  • 1,645
  • 1
  • 10
  • 25
  • Thank you Safwan. Do you know why replacing these values into: `rt = datetime.datetime(now.year,now.month,now.day,now.hour)` I get `AttributeError: type object 'datetime.datetime' has no attribute 'datetime'`? (In 8 minutes I will mark your answer. It is currently not allowing me) – LdM Apr 11 '21 at 02:10
  • After the line `from datetime import datetime`, `datetime` is actually `datetime.datetime`. If you want the core `datetime` module, I suggest you add this line, too - `import datetime as dt`. But the function you're using does not require the core module, it requires only `datetime.datetime`. So change your code to `datetime(now.year,now.month,now.day,now.hour)`. Not that I see much use in it, you can do `datetime.now()` instead. – Safwan Samsudeen Apr 11 '21 at 02:14
  • Thank you Safwan. The problem is something in the format, I guess. Following this answer (replacing the date into the reftime (https://stackoverflow.com/questions/67038185/from-string-to-datetime-looking-at-the-current-local-time), it returns no values – LdM Apr 11 '21 at 02:18