How to add string and datetime format - python

i have a string like this (YYYY/MM/DD/HH/MM):
0000/01/00/00/00/00
I need to add this string and now's data. I give now's data via
datetime.now()
I try to use:
conv_data = datetime.strptime('0000/01/00/00/00/00', '%Y/%m/%d/%H/%M/%S')
conv_data + datetime.now()
but it doesn't work because Year, Month and etc. must be greater then zero. Can you help me to solve my problem, please.

Another way of doing so would be using split()
Ex.
from datetime import datetime
date_string = '0000/01/00/00/00/00'
date_array = date_string.split('/')
conv_data = datetime.strptime('-'.join(date_array [0:3])+" " + ':'.join(date_array [3:]), '%Y-%m-%d %H:%M:%S')

I solved using
date = '0000/01/00/00/00/00'
now = datetime.now().strftime('%Y/%m/%d/%H/%M/%S')
date_res = []
for now, date in zip(now.split('/'), date.split('/')):
date_res.append(str(int(now)+ int(date)))
print('/'.join(date_res))

Would it work to just add a month to the current datetime?
In that case you could do this:
from dateutil.relativedelta import relativedelta
datetime.now() + relativedelta(months=+1)
Output: datetime.datetime(2021, 2, 11, 11, 52, 34, 952997)
Edit for YYYY/MM/DD/HH/MM format:
date_res2 = datetime.now() + relativedelta(months=+1)
date_res2.strftime('%Y/%m/%d/%H/%M')
Output: '2021/02/12/09/33'

Related

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

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"

python: adding any number of days to date

I am hoping someone can point me in the right direction in working with dates and timedelta.
my understanding is that to add any number (ex: 10 days) to a date, you need to convert it to a timedelta.
if that is correct, how can I add any number to a date when it is an integer?
any documentation or links would be great - thank you.
code example, my date is as follows:
x = 20100103 (formatted as YYYYMMDD)
>>> import datetime
>>> today = datetime.datetime.now().date()
>>> today
datetime.date(2016, 6, 14)
>>> today + datetime.timedelta(days=10)
datetime.date(2016, 6, 24)
There's no need to convert it to a timedelta. Just use the timedelta function, if you want to add days, use days=N, for hours, timedelta(hours=20)
x=20100103
x2 = int((datetime.datetime.strptime(str(x),"%Y%m%d") + datetime.timedelta(days=10)).strftime("%Y%m%d"))
to break it down
x=20100103
x_as_datetime = datetime.datetime.strptime(str(x),"%Y%m%d")
new_datetime = x_as_datetime + datetime.timedelta(days=10) #add your timedelta
x2 = new_datetime.strftime("%Y%m%d") # format it back how you want
int(x2) # if you just want an integer ...
from datetime import datetime
from datetime import timedelta
StartDate = "20100103"
Date = datetime.strptime(StartDate, "%Y%m%d")
EndDate = Date + timedelta(days=10)

Expand date to the beginning and end datetime for the day

Based on the current time (datetime.now()) I want to expand this to cover the whole days time.
Right now I have been using:
start = (datetime.now() - timedelta(days=1)).strftime('%Y-%m-%d %H:%M:%S')
end = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
Problem is that this is 24 hours from the current date. If it is 12pm noon that means it should only look back 12 hours as I want to search for the current days records.
How can I accomplish this in Python?
I hope this makes sense, I just gave very descriptive variable names
from datetime import datetime
from datetime import timedelta
now = datetime.now()
start_of_day = datetime(now.year,now.month,now.day)
delta_since_start_of_day = now - start_of_day
delta_till_end_of_day = timedelta(days=1) - delta_since_start_of_day
end_of_day = start_of_day + timedelta(days=1)
Here's another solution that directly resets the time - no math required. Uses datetime.replace():
now = datetime.now()
day_start = now.replace(hour=0, minute=0, second=0, microsecond=0)
day_end = day_start + timedelta(hours=24)
It seems you could accomplish what you wish like so:
from datetime import datetime, time
now = datetime.now()
start = datetime.combine(now, time.min) # datetime.datetime(2021, 11, 5, 0, 0)
end = datetime.combine(now, time.max) # datetime.datetime(2021, 11, 5, 23, 59, 59, 999999)
No need for maths, replacing, timedeltas.
I just use datetime.time.max in this way:
now = datetime.now()
day_end = datetime.datetime.combine(now, datetime.time.max)

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

Django date YYYY-MM-DD

I get date in format(YYYY-MM-DD)
Then I want to add timedelta
mydate + timedelta(days=1)
and I get error
coercing to Unicode: need string or buffer, datetime.timedelta found
mydate is a string. Try doing this:
from datetime import datetime
parsed_date = datetime.strptime(mydate, "%Y-%m-%d")
new_date = parsed_date + timedelta(days=1)
Data sent by the client will be sent as a Unicode and you have to parse it on server side
datetime.strptime(date, '%Y-%m-%d')
If it's part of a form, the data should be reformatted automatically when cleaned (though you might need to configure the field to accept the format you expect).
You have to convert your string date to python datetime:
>>> from datetime import datetime, timedelta
>>> dt_str = "2013/10/11"
>>> dt = datetime.strptime(dt_str, "%Y/%m/%d")
>>> new_dt = dt + timedelta(days=1)
>>> print new_dt
datetime.datetime(2013, 10, 12, 0, 0)
If you now want to get the date as string:
>>> print new_dt.strftime("%Y/%m/%d")
'2013/10/12'

Categories