How to get tomorrow's date in isoformat using datetime - python

I'm trying to get tomorrow's date using the datetime module, just as you can get today's date. As far as i know, there isn't a simple function that returns the next day's date, but from googling i found that you can use timedelta to increment days.
However, i need the date to be in isoformat, just as today's date.
This is what i currently have:
now = datetime.datetime.utcnow().isoformat() + 'Z'
tomorrow = now + str(datetime.timedelta(days=1))
print(now)
print(tomorrow)
However, this returns the following for now and today respectively:
2021-04-18T11:18:30.363421Z
2021-04-18T11:18:30.363421Z1 day, 0:00:00
I need the next day's date to be the same format (isoformat) as today's date. Anyone know how to do this properly?

The order of the operations is incorrect. You can try:
>>> now = datetime.datetime.utcnow()
>>> tomorrow = now + datetime.timedelta(days=1)
>>> now = now.isoformat() + 'Z'
>>> tomorrow = tomorrow.isoformat() + 'Z'
>>> now
'2021-04-18T11:27:57.810303Z'
>>> tomorrow
'2021-04-19T11:27:57.810303Z'

Related

Python: Comparing two dates

I would like to know how many days are passed from a x ago to today
I wrote this:
from datetime import datetime
timestamp = 1629195530 # A month ago
before = datetime.fromtimestamp(timestamp)
daysBefore = before.strftime("%d")
now = datetime.now()
today = now.strftime("%d")
print(f"daysBefore {daysBefore} - today {today}")
daysPassed = int(today) - int(daysBefore)
But so it seems, daysBefore is returning the days of the month, I can't get my head around this :(
Exact format with date time hour minute accuracy
from datetime import datetime
timestamp = 1629195530 # A month ago
before = datetime.fromtimestamp(timestamp)
now = datetime.now()
print(now - before))
print(f"daysBefore {daysBefore} - today {today}")
The reason this doesn't work is that it gives the day of the month. For example 17th of July and 17th of August will give a difference of zero days.
Therefore the recommend method is as #abdul Niyas P M says, use the whole date.time format to subtract two dates and afterwards extract the days.
Your issue is due to this: strftime("%d")
You are converting you date to a string and then to an int to make the difference. You can just use the datetime to do this for you:
timestamp = 1629195530 # A month ago
before = datetime.fromtimestamp(timestamp)
now = datetime.now()
print(f"daysBefore {before} - today {now}")
daysPassed = now - before
print(daysPassed.days)

Convert timestamp to time only

I'm getting the calendar results from outlook, fetching only the Start time and the Subject of each calendar item.
import win32com, win32com.client
import datetime, time, pytz
def getCalendarEntries():
Outlook = win32com.client.Dispatch("Outlook.Application")
appointments = Outlook.GetNamespace("MAPI").GetDefaultFolder(9).Items
appointments.Sort("[Start]");
appointments.IncludeRecurrences = "True"
today = datetime.datetime.today().date().strftime("%Y-%d-%m")
tomorrow = (datetime.date.today() + datetime.timedelta(days=1)).strftime("%Y-%d-%m")
appointments = appointments.Restrict("[Start] >= '" +today+"' AND [Start] < '"+tomorrow+"'");
events={'Start':[],'Subject':[]}
for a in appointments:
events['Start' ].append(a.Start );
events['Subject'].append(a.Subject)
return events
calendar = getCalendarEntries();
n=len(calendar['Start']);
i=0;
while( n ):
print(
calendar['Start'][i] ,
calendar['Subject'][i]
);
n-=1;
i+=1;
This is the result, and it is correct:
$ py test_outlook.py
2019-12-06 10:00:00+00:00 test apointment
What I need now is to manipule this data above to get only the time: 10:00, so that I can do calculations and find out how much time there is until the event starts... like if it's 10min away, 1h away, etc.
I really have no idea on how to do it... anyone has any idea?
Uri Goren seems to have answered the question here: https://stackoverflow.com/a/38992623/8678978
You need to use strptime with the datetime format to get a date object, and then you can extract the time portion.
dateString = '2019-12-06 10:00:00+00:00'
dateObject = datetime.datetime.strptime(str[0:19], '%Y-%m-%d %H:%M:%S')
Now you have a date object and can get the time parts using:
dateObject.hour
dateObject.minute
dateObject.second
I am not sure what type getCalendarEntries returns. You can find out by adding an additional temporary line in your program:
print(type(calendar['Start'][i]))
If it is a datetime object, you can simply query the hour attribute:
hours = calendar['Start'][i].hour
If getCalendarEntries returns a POSIX timestamp, you can first convert it to a Python datetime object and then query the hour
dt = datetime.fromtimestamp(calendar['Start'][i])
hours = dt.hour
If it is a string, you can parse it using datetime.fromisoformat:
dt = datetime.datetime.fromisoformat(calendar['Start'][i])
hours = dt.hour

How to get the month start date from input_date

I am developing an API where the user enters an input date in this format: 2019-07-29 which will be converted to date time to get '2019-07-29'. This will be used in queries against the database.
input_date = str(input_date)
input_date_formatted = "'" + datetime.strptime(input_date, '%Y-%m-%d').strftime('%Y-%m-%d') + "'"
I am trying to get the start of the month date for whichever input_date in this fashion: XXXX-XX-01. Any ideas?
If you are using it as a datetime and not a string later you can do this as follows (assuming input_date is a string):
date = datetime.strptime(input_date, '%Y-%m-%d')
first_day_of_month = date.replace(day=1)
I am assuming that you might need the actual input and the start of the month date.
By that logic the following code might just work out for you.
from datetime import datetime
input_date = '2019-07-29'
input_date = str(input_date)
input_date_formatted = "'" + datetime.strptime(input_date, '%Y-%m-%d').strftime('%Y-%m-%d') + "'"
input_date_formatted = input_date_formatted[:9]+"01'"
print(input_date_formatted)
from datetime import datetime
input_date = '2019-07-29'
input_date_object = datetime.strptime(input_date, '%Y-%m-%d')
first_date_object = input_date_object.date().replace(day=1)
print (first_date_object) # <class 'datetime.date'>
print (first_date_object.strftime('%Y-%m-%d')) # <class 'str'>
output:
2019-07-01
2019-07-01
NOTE:
Use datetime.date to get just date without hours:minutes:seconds
The function replace() is to replace specific or all the attributes
of a datetime object.
Date attributes of a datetime object that can be replaced by the
replace() function:
year
month
day

How to subtract from date given as user input?

So I'm trying to subtract one day from a users input of 2018-02-22 for example. Im a little bit stuck with line 5 - my friend who is is leaps and bounds ahead of me suggested I try this method for subtracting one day.
In my online lessons I haven't quite got to datetime yet so Im trying to ghetto it together by reading posts online but got a stuck with the error :
TypeError: descriptor 'date' of 'datetime.datetime' object needs an argument
from datetime import datetime, timedelta
date_entry = input('Enter a date in YYYY-MM-DD format')
year, month, day = map(int, date_entry.split('-'))
date1 = datetime.date()
new = date1.replace(day=date1.day-1, hour=1, minute=0, second=0, microsecond=0)
print (new)
So my aim is the get the out put 2018-02-21 if I put in 2018-02-22.
Any help would be amazing :)
First of all a timedeltais best used for the purpose of doing date arithmetcs. You import timedelta but don't use it.
day = timedelta(days=1)
newdate = input_datetime - day
Second problem is you're not initializing a date object properly. But in this case it would be better to use datetime as well as strptime to parse the datetime from the input string in a certain format.
date_entry = input('Enter a date in YYYY-MM-DD format')
input_date = datetime.strptime(date_entry, "%Y-%m-%d")
day = timedelta(days=1)
newdate = input_datetime - day
from datetime import datetime, timedelta
date_entry = input('Enter a date in YYYY-MM-DD format')
date1 = datetime.strptime(date_entry, '%Y-%m-%d')
print date1+timedelta(1)
Maybe you need something like this
from datetime import datetime, timedelta
date_entry = input('Enter a date in YYYY-MM-DD format ')
# convert date into datetime object
date1 = datetime.strptime(date_entry, "%Y-%m-%d")
new_date = date1 -timedelta(days=1) # subtract 1 day from date
# convert date into original string like format
new_date = datetime.strftime(new_date, "%Y-%m-%d")
print(new_date)
Output:
Enter a date in YYYY-MM-DD format 2017-01-01
'2016-12-31'

Python count start date + days

I am making a program where I input start date to dataStart(example 21.10.2000) and then input int days dateEnd and I convert it to another date (example 3000 = 0008-02-20)... Now I need to count these dates together, but I didn't managed myself how to do that. Here is my code.
from datetime import date
start=str(input("type start date (DD.MM.YYYY)"))
end=int(input("how many days from it?"))
dataStart=start.split(".")
days=int(dataStart[0])
months=int(dataStart[1])
years=int(dataStart[2])
endYears=0
endMonths=0
endDays=0
dateStart = date(years, months, days)
while end>=365:
end-=365
endYears+=1
else:
while end>=30:
end-=30
endMonths+=1
else:
while end>=1:
end-=1
endDays+=1
dateEnd = date(endYears, endMonths, endDays)
For adding days into date, you need to user datetime.timedelta
start=str(input("type start date (DD.MM.YYYY)"))
end=int(input("how many days from it?"))
date = datetime.strptime(start, "%d.%m.%Y")
modified_date = date + timedelta(days=end)
print(datetime.strftime(modified_date, "%d.%m.%Y"))
You may use datetime.timedelta to add certain units of time to your datetime object.
See the answers here for code snippets: Adding 5 days to a date in Python
Alternatively, you may wish to use the third-party dateutil library if you need support for time additions in units larger than weeks. For example:
>>> from datetime import datetime
>>> from dateutil import relativedelta
>>> one_month_later = datetime(2017, 5, 1) + relativedelta.relativedelta(months=1)
>>> one_month_later
>>> datetime.datetime(2017, 6, 1, 0, 0)
It will be easier to convert to datetime using datetime.datetime.strptime and for the part about adding days just use datetime.timedelta.
Below is a small snippet on how to use it:
import datetime
start = "21.10.2000"
end = 8
dateStart = datetime.datetime.strptime(start, "%d.%m.%Y")
dateEnd = dateStart + datetime.timedelta(days=end)
dateEnd.date() # to get the date format of the endDate
If you have any doubts please look at the documentation python3/python2.

Categories

Resources