brenny K
brenny K

Reputation: 1

How to convert a datetime to date in Python?

I'm getting today's date & other datetime date is coming in. That datetime I want to convert it to normal date. But it keep throwing errors.

Below is my code. import time import datetime from datetime import date from datetime import datetime,timedelta

get todays date

today_date = date.today()
#print(today_date)

# get user information from the group
pagination_item = server.groups.populate_users(mygroup)

# print the names of the users
for user in mygroup.users:
    # user.last_login is present in datetime format, converted that to date format
    #lastlogin = datetime.date(user.last_login) 
    **lastlogin = user.last_login.date()**
    print(type(lastlogin))
# difference between today & last login date
    difference = today_date - lastlogin
    if difference.days > 120:
        print(user.name,lastlogin,difference)

Errror which I'm getting

<class 'datetime.date'> Traceback (most recent call last): File "C:\Bhavana\user_list_90_days.py", line 37, in lastlogin = user.last_login.date() AttributeError: 'NoneType' object has no attribute 'date'

Upvotes: 0

Views: 7389

Answers (1)

Hitesh Kumar
Hitesh Kumar

Reputation: 19

You may use this

from datetime import datetime  
datetime_obj = datetime.now()
  
print(datetime_obj)
  
date = datetime_obj.date()

print(date) 

Output shall be:

2021-08-07 06:30:20.227879

2021-08-07

Upvotes: 2

Related Questions