I am very much new to Python and need to extract previous day data from RESTAPI and in my RESTAPI request i need to provide QueryStartDate and QueryEndDate. Till now for testing i am providing the previous day date(sysdate-1) manually. But now as i wanted to automated the process, i want to apply Python function to always get the previous date so that i can extract the whole day data from previous day.
I am using UTC time zone so this part T12:00:00.000Z i need to keep as it is otherwise my request to RESTAPI will not run. So i just need to change date part.
"QueryStartDate": "2021-09-02T12:00:00.000Z"
"QueryEndDate": "2021-09-02T12:10:00.000Z"
I tried to apply datetime.now() - timedelta(1) function to get previous day date but not sure due to syntax issue the RESTAPI request is throwing an error.
If you need the string value of the previous day in the format of either:
Format 1: "2021-09-02T00:00:00.000000+0000"
Format 2: "2021-09-02T00:00:00.000000Z"
Which ranges from the start time 00:00:00.000000 to the end time 23:59:59.999999, you can use datetime.strftime() along with the time.min and time.max:
from datetime import datetime, time, timedelta, timezone
yesterday_dt = datetime.now(timezone.utc) - timedelta(days=1)
yesterday_start_dt = datetime.combine(yesterday_dt, time.min, tzinfo=timezone.utc)
yesterday_end_dt = datetime.combine(yesterday_dt, time.max, tzinfo=timezone.utc)
format1 = "%Y-%m-%dT%H:%M:%S.%f%z"
format2 = "%Y-%m-%dT%H:%M:%S.%fZ"
queryStartDate_format1 = yesterday_start_dt.strftime(format1)
queryEndDate_format1 = yesterday_end_dt.strftime(format1)
print("Format 1:")
print(queryStartDate_format1)
print(queryEndDate_format1)
queryStartDate_format2 = yesterday_start_dt.strftime(format2)
queryEndDate_format2 = yesterday_end_dt.strftime(format2)
print("Format 2:")
print(queryStartDate_format2)
print(queryEndDate_format2)
Output
Format 1:
2021-09-02T00:00:00.000000+0000
2021-09-02T23:59:59.999999+0000
Format 2:
2021-09-02T00:00:00.000000Z
2021-09-02T23:59:59.999999Z
Update
Here is a version if the import is based on the root datetime.
import datetime
yesterday_dt = datetime.datetime.now(datetime.timezone.utc) - datetime.timedelta(days=1)
yesterday_start_dt = datetime.datetime.combine(yesterday_dt, datetime.time.min, tzinfo=datetime.timezone.utc)
yesterday_end_dt = datetime.datetime.combine(yesterday_dt, datetime.time.max, tzinfo=datetime.timezone.utc)
format1 = "%Y-%m-%dT%H:%M:%S.%f%z"
format2 = "%Y-%m-%dT%H:%M:%S.%fZ"
queryStartDate_format1 = yesterday_start_dt.strftime(format1)
queryEndDate_format1 = yesterday_end_dt.strftime(format1)
print("Format 1:")
print(queryStartDate_format1)
print(queryEndDate_format1)
queryStartDate_format2 = yesterday_start_dt.strftime(format2)
queryEndDate_format2 = yesterday_end_dt.strftime(format2)
print("Format 2:")
print(queryStartDate_format2)
print(queryEndDate_format2)
Use those line of code may be help you to find previous day
import datetime
Previous_Date = datetime.datetime.today() - datetime.timedelta(days=1)
print (Previous_Date)
If your using UTC timezone then try:
from datetime import datetime, timedelta, timezone
todayUTC = datetime.now(timezone.utc).date()
yesterdayUTC = today - timedelta(1)
print(todayUTC, yesterdayUTC)
Related
I'm trying to make a reminder app, but I can't find out how to show if the entered date is the current date. To give an example:
I added a reminder on December 19, 2021 at 17:45, and I want to know if this date is before today's date.
You can use datetime.datetime.strptime() to convert string to datetime object. Then you can calculate time delta with to check how much time is left.
import datetime
reminder = datetime.datetime.strptime('12/19/2021, 19:11:14',
"%m/%d/%Y, %H:%M:%S")
print(datetime.datetime.now()) # 2021-12-12 17:24:01.573420
time_delta = reminder - datetime.datetime.now()
print(time_delta.seconds) # 6432
print(time_delta.days) # 7
If the current date is after the reminder date, days will be negative.
You can use the python's builtin datetime module.
You can import it like this:
from datetime import datetime
To convert the reminder string to a date time object, you can use the strptime() function.
reminder_date = "December 19, 2021 at 17:45"
reminder = datetime.strptime(reminder_date, "%B %d, %Y at %H:%M")
Next, get the current datetime object.
current = datetime.now()
Finally, you can compare them using python's builtin comparison operators as follows.
if reminder < current:
print("passed")
else:
print("future")
From what I've seen this should be working even if it's not the prettiest. I've tried plenty of things but doesn't seem to work with anything and best I've been able to do is change the error message lol.
try:
date = dt.datetime.now()
d1 = date - timedelta(days=1)
d1.strftime('%Y%m%d')
url = 'http://regsho.finra.org/FNQCshvol' + d1 + '.txt'
Try the following:
from datetime import timedelta
import datetime as dt
date = dt.datetime.now()
d1 = date - timedelta(days=1)
d1 = d1.strftime('%Y%m%d') # I changed this line
url = 'http://regsho.finra.org/FNQCshvol' + d1 + '.txt'
strftime() returns the string, it does not convert the date itself to a string.
I modified your code a little. There were a couple of mistake in it and it wasn't running.
The main problem you were running into is you were trying to concatenate a string with a datetime object. You applied the strftime correctly but you didn't save the string. That string you can concatenate with another string.
import datetime as dt
date = dt.datetime.now()
d1 = date - dt.timedelta(days=1)
d1_string = d1.strftime('%Y%m%d')
url = 'http://regsho.finra.org/FNQCshvol{timestamp}.txt'.format(timestamp=d1_string)
In your code you don't assign result of datetime.strftime() to a variable. Solution is simple:
from datetime import datetime, timedelta
current_date = datetime.now() # store current date and time
required_date = current_date - timedelta(days=1) # substitute 1 day
str_date = required_date.strftime('%Y%m%d') # apply formatting
url = f'http://regsho.finra.org/FNQCshvol{str_date}.txt'
You can also do it in one line (which makes code much less readable):
url = f"http://regsho.finra.org/FNQCshvol{(datetime.now() - timedelta(days=1)).strftime('%Y%m%d')}.txt"
Kindly help below my query:
I got an estimated time from API server like below:
2019-09-25T20:11:23+08:00
it seems like iso 8601 standard with timezone.
I would like to know how to calculate how many days, hours, minutes and seconds left from above value to the current time.
import datetime
Receved_time_frim_API = "2019-09-25T20:11:23+08:00"
Current_time = datetime.datetime.now()
left_days =
left_hour =
left_min =
left_sec =
Your time string contains timezone info. According to https://stackoverflow.com/a/13182163/12112986 it's easy to convert it to datetime object in python 3.7
import datetime
received = datetime.datetime.fromisoformat(Receved_time_frim_API)
In previous versions there is no easy oneliner to convert string with timezone to datetime object. If you're using earlier python version, you can try something crude, like
>>> date, timezone = Receved_time_frim_API.split("+")
>>> tz_hours, tz_minutes = timezone.split(":")
>>> date = datetime.datetime.strptime(date, "%Y-%m-%dT%H:%M:%S")
>>> date -= datetime.timedelta(hours=int(tz_hours))
>>> date -= datetime.timedelta(minutes=int(tz_minutes))
Note that this will work only in case of positive timezones
To substract two datetime objects use
td = date - Current_time
left_days = td.days
left_hour = td.seconds // 3600
left_min = (td.seconds//60)%60
left_sec = td.seconds % 60
Okay first you need to parse the Receved_time_frim_API into datetime format:
from dateutil import parser
Receved_time_frim_API = parser.parse("2019-09-25T20:11:23+08:00")
But you can't just substract this from your Current_time, because datetime.now() is not aware of a timezone:
from datetime import timezone
Current_time = datetime.datetime.now().replace(tzinfo=timezone.utc)
print (Current_time-Receved_time_frim_API)
The result is a datetime.timedelta
I want to add hours to a datetime and use:
date = date_object + datetime.timedelta(hours=6)
Now I want to add a time:
time='-7:00' (string) plus 4 hours.
I tried hours=time+4 but this doesn't work. I think I have to int the string like int(time) but this doesn't work either.
Better you parse your time like below and access datetime attributes for getting time components from the parsed datetime object
input_time = datetime.strptime(yourtimestring,'yourtimeformat')
input_seconds = input_time.second # for seconds
input_minutes = input_time.minute # for minutes
input_hours = input_time.hour # for hours
# Usage: input_time = datetime.strptime("07:00","%M:%S")
Rest you have datetime.timedelta method to compose the duration.
new_time = initial_datetime + datetime.timedelta(hours=input_hours,minutes=input_minutes,seconds=input_seconds)
See docs strptime
and datetime format
You need to convert to a datetime object in order to add timedelta to your current time, then return it back to just the time portion.
Using date.today() just uses the arbitrary current date and sets the time to the time you supply. This allows you to add over days and reset the clock to 00:00.
dt.time() prints out the result you were looking for.
from datetime import date, datetime, time, timedelta
dt = datetime.combine(date.today(), time(7, 00)) + timedelta(hours=4)
print dt.time()
Edit:
To get from a string time='7:00' to what you could split on the colon and then reference each.
this_time = this_time.split(':') # make it a list split at :
this_hour = this_time[0]
this_min = this_time[1]
Edit 2:
To put it all back together then:
from datetime import date, datetime, time, timedelta
this_time = '7:00'
this_time = this_time.split(':') # make it a list split at :
this_hour = int(this_time[0])
this_min = int(this_time[1])
dt = datetime.combine(date.today(), time(this_hour, this_min)) + timedelta(hours=4)
print dt.time()
If you already have a full date to use, as mentioned in the comments, you should convert it to a datetime using strptime. I think another answer walks through how to use it so I'm not going to put an example.
I want to get the 20th of previous month, given the current_date()
I am trying to use time.strftime but not able to subtract the value from it.
timestr = time.strftime("%Y-(%m-1)%d")
This is giving me error. The expected output is 2019-03-20 if my current_date is in April. Not sure how to go about it.
I read the posts from SO and most of them address getting the first day / last day of the month. Any help would be appreciated.
from datetime import date, timedelta
today = date.today()
last_day_prev_month = today - timedelta(days=today.day)
twenty_prev_month = last_day_prev_month.replace(day=20)
print(twenty_prev_month) # 2019-03-20
Use datetime.replace
import datetime
current_date = datetime.date.today()
new_date = current_date.replace(
month = current_date.month - 1,
day = 20
)
print(new_date)
#2019-03-20
Edit
That won't work for Jan so this is a workaround:
import datetime
current_date = datetime.date(2019, 2, 17)
month = current_date.month - 1
year = current_date.year
if not month:
month, year = 12, year - 1
new_date = datetime.date(year=year, month=month, day=20)
I imagine it is the way dates are parsed. It is my understanding that with your code it is looking for
2019-(03-1)20 or 2019-(12-1)15, etc..
Because the %y is not a variable, but a message about how the date is to be expected within a string of text, and other characters are what should be expected, but not processed (like "-")
This seems entirely not what you are going for. I would just parse the date like normal and then reformat it to be a month earlier:
import datetime
time = datetime.datetime.today()
print(time)
timestr = time.strftime("%Y-%m-%d")
year, month, day = timestr.split("-")
print("{}-{}-{}".format(year, int(month)-1, day))
This would be easier with timedelta objects, but sadly there isn't one for months, because they are of various lengths.
To be more robust if a new year is involved:
import datetime
time = datetime.datetime.today()
print(time)
timestr = time.strftime("%Y-%m-%d")
year, month, day = timestr.split("-")
if month in [1, "01", "1"]: # I don't remember how January is represented
print("{}-{}-{}".format(int(year) - 1, 12, day)) # use December of last year
else:
print("{}-{}-{}".format(year, int(month)-1, day))
This will help:
from datetime import date, timedelta
dt = date.today() - timedelta(30)// timedelta(days No.)
print('Current Date :',date.today())
print(dt)
It is not possible to do math inside a string passed to time.strftime, but you can do something similar to what you're asking very easily using the time module
in Python 3
# Last month
t = time.gmtime()
print(f"{t.tm_year}-{t.tm_mon-1}-20")
or in Python 2
print("{0}-{1}-{2}".format(t.tm_year, t.tm_mon -1, 20))
If you have fewer constraints, you can just use the datetime module instead.
You could use datetime, dateutil or arrow to find the 20th day of the previous month. See examples below.
Using datetime:
from datetime import date
d = date.today()
month, year = (d.month-1, d.year) if d.month != 1 else (12, d.year-1)
last_month = d.replace(day=20, month=month, year=year)
print(last_month)
Using datetime and timedelta:
from datetime import date
from datetime import timedelta
d = date.today()
last_month = (d - timedelta(days=d.day)).replace(day=20)
print(last_month)
Using datetime and dateutil:
from datetime import date
from dateutil.relativedelta import relativedelta # pip install python-dateutil
d = date.today()
last_month = d.replace(day=20) - relativedelta(months=1)
print(last_month)
Using arrow:
import arrow # pip install arrow
d = arrow.now()
last_month = d.shift(months=-1).replace(day=20).datetime.date()
print(last_month)