1

Hi I am trying to subtract two dates, one coming from MongoBd as date format and the other as DateTime.now() on Python. The format is not the one I need. I would like to show just the day but instead, it is showing this format: "1 day, 9:06:17.913564 " but I would like to show just this "1 day" Any feedback will be appreciated.

date coming from Mongo as a date format

enter code here

 mongo_date = 2021-12-31T06:00:00.000+00:00 
 todayday = datetime.now()
 duedate = mongo_date - todayday
 

duedate= 1 day, 9:06:17.913564

I would like to show the duedate as "1 day"

Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
ZEQUET
  • 51
  • 1
  • 7
  • Am I missing something, why haven't you just used `datetime.strftime()` to accomplish this...this is the standard way to convert time to strings... Other than that you can obviously just parse the string to cut off the data you don't need by splitting from a `,` which is also pretty standard...what have you tried? – ViaTech Dec 30 '21 at 03:07
  • I tried that but I am receiving : AttributeError: 'datetime.timedelta' object has no attribute 'strftime' new_str = duedate.strftime() – ZEQUET Dec 30 '21 at 03:10
  • Please read https://stackoverflow.com/help/minimal-reproducible-example. The code you show isn't runnable. If you can reproduce the problem using the standard library (with a hard-coded date) then you should do so. If you need MongoDB then hard-code some simple example data and show the necessary code. We should be able to copy and paste the code you show, without modification, and re-create the problem. – Karl Knechtel Dec 30 '21 at 03:19
  • That said: does https://stackoverflow.com/questions/538666/format-timedelta-to-string answer your question? You [should](https://meta.stackoverflow.com/questions/261592) also try to do some research before asking here. In this case, it was as simple as putting `python format timedelta` into a search engine. – Karl Knechtel Dec 30 '21 at 03:21
  • I found a solution doing this : duedate = str(duedate).split(",")[0] – ZEQUET Dec 30 '21 at 03:35

1 Answers1

1

How about this: (Simplified based on @MrFuppes comment avoiding pytz import.)

import datetime

mongo_date = "2021-12-31T06:00:00.000+00:00" 
mongo_date = datetime.datetime.fromisoformat(mongo_date)

#Since your mongo_date is in UTC time zone, I'm using UTC for todayday:
todayday = datetime.datetime.now(datetime.timezone.utc)

duedate = mongo_date - todayday #this is a timedelta object
print("Due date is {} days".format(duedate.days))
BioData41
  • 862
  • 9
  • 15