TRYING to subtract days from datetime and convert it to a string - python

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"

Related

get the data for the previous day in Python

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)

Finding difference in day between today's date and a entered date

I am currently trying to construct a function that takes a date string and returns the number of days from that date until now. It will return 0 if it detects that the format is wrong, with the input date string format being Day/Month/Year (e.g. 12/3/21). The number should be negative if it is a past date (e.g. today is 14/3/21, the input date is 3/3/21, the function should return -11). This is my code so far but it keeps returning 0:
from datetime import datetime
from datetime import date
def convert_date(input_date):
try:
current_date = date.today()
d1 = datetime.strptime(input_date, '%d/%m/%y')
d2 = datetime.strptime(current_date, '%d/%m/%y')
delta = d1 - d2
return delta.day
except:
return 0
I am very unsure on what I have done wrong, as I have done a lot of research but have not found a solution. Hopefully someone can provide further clarification, thanks
(Also i am using the Datetime package)
These are basics and you need to understand datetime module well. Hope this solves your problem.
from datetime import datetime
def convert_date(input_date):
try:
current_date = datetime.today()
d1 = datetime.strptime(input_date, '%d/%m/%y')
delta = d1 - current_date
return delta.days
except ValueError:
return 0

How to minus time that received from API server and current time in Python

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

How to add a certain time to a datetime?

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.

Python - Get Yesterday's date as a string in YYYY-MM-DD format

As an input to an API request I need to get yesterday's date as a string in the format YYYY-MM-DD. I have a working version which is:
yesterday = datetime.date.fromordinal(datetime.date.today().toordinal()-1)
report_date = str(yesterday.year) + \
('-' if len(str(yesterday.month)) == 2 else '-0') + str(yesterday.month) + \
('-' if len(str(yesterday.day)) == 2 else '-0') + str(yesterday.day)
There must be a more elegant way to do this, interested for educational purposes as much as anything else!
You Just need to subtract one day from today's date. In Python datetime.timedelta object lets you create specific spans of time as a timedelta object.
datetime.timedelta(1) gives you the duration of "one day" and is subtractable from a datetime object. After you subtracted the objects you can use datetime.strftime in order to convert the result --which is a date object-- to string format based on your format of choice:
>>> from datetime import datetime, timedelta
>>> yesterday = datetime.now() - timedelta(1)
>>> type(yesterday)
>>> datetime.datetime
>>> datetime.strftime(yesterday, '%Y-%m-%d')
'2015-05-26'
Note that instead of calling the datetime.strftime function, you can also directly use strftime method of datetime objects:
>>> (datetime.now() - timedelta(1)).strftime('%Y-%m-%d')
'2015-05-26'
As a function:
from datetime import datetime, timedelta
def yesterday(frmt='%Y-%m-%d', string=True):
yesterday = datetime.now() - timedelta(1)
if string:
return yesterday.strftime(frmt)
return yesterday
example:
In [10]: yesterday()
Out[10]: '2022-05-13'
In [11]: yesterday(string=False)
Out[11]: datetime.datetime(2022, 5, 13, 12, 34, 31, 701270)
An alternative answer that uses today() method to calculate current date and then subtracts one using timedelta(). Rest of the steps remain the same.
https://docs.python.org/3.7/library/datetime.html#timedelta-objects
from datetime import date, timedelta
today = date.today()
yesterday = today - timedelta(days = 1)
print(today)
print(yesterday)
Output:
2019-06-14
2019-06-13
>>> import datetime
>>> datetime.date.fromordinal(datetime.date.today().toordinal()-1).strftime("%F")
'2015-05-26'
Calling .isoformat() on a date object will give you YYYY-MM-DD
from datetime import date, timedelta
(date.today() - timedelta(1)).isoformat()
I'm trying to use only import datetime based on this answer.
import datetime
oneday = datetime.timedelta(days=1)
yesterday = datetime.date.today() - oneday

Categories