Home > OS >  Format date in datetime
Format date in datetime

Time:08-29

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

CodePudding user response:

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

CodePudding user response:

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"

CodePudding user response:

>>> 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.

  • Related