jimmy
jimmy

Reputation: 45

Format date in datetime

i have a date which returns in format of datetime.datetime(2022, 8, 29, 0, 3, 17, 37389) i want it to be formatted to datetime.datetime(2022, 8, 29, 0, 0).

 def some_method_to_return()
     due_date = timezone.datetime.strptime(
       Aug 29, 2022, '%B %d, %Y'
    )
    return due_date

due_date = datetime.datetime(2022, 8, 29, 0, 0)

the need to check todays date with due_date if its true how can format today's date in due_date form

Upvotes: 0

Views: 925

Answers (3)

aayushgupta
aayushgupta

Reputation: 74

>>> from datetime import datetime
>>> now = datetime.now()
>>> now_string = now.strftime('%Y %m %d %H %M')
>>> now = datetime.strptime(now_string, "%Y %m %d %H %M")
>>> now
datetime.datetime(2022, 8, 29, 13, 21)

You basically have to convert it to a string first using the strftime function. Then using strptime you can convert it back to a datetime object.

Upvotes: 0

Daniel Kanzel
Daniel Kanzel

Reputation: 73

I'm not sure if this is what you need, but it might work.

due_date = datetime.datetime(2022, 8, 29, 0, 0)
today = datetime.datetime.now()
def is_today():
    if due_date.date() == today.date():
        return today.replace(hour = 0, minute=0, second=0, microsecond=0)
    else:
        return "Not today"

Upvotes: 0

jack
jack

Reputation: 281

from datetime import datetime

def keepJustTheDate(d:datetime):
    return d.replace(hour=0, minute=0, second=0, microsecond=0)

Just look into the datetime docs https://docs.python.org/3/library/datetime.html#datetime.date.replace

Upvotes: 1

Related Questions