Converting a date string to date format then do subtraction - python

I am given two dates as strings below, and I want to subtract them to get the number 16 as my output. I tried converting them to date format first and then doing the math, but it didn't work.
from datetime import datetime
date_string = '2021-05-27'
prev_date_string = '2021-05-11'
a = datetime.strptime(date_string '%y/%m/%d')
b = datetime.strptime(prev_date_string '%y/%m/%d')
c = a - b
print (c)

There are two problems with the strptime calls. First, they are missing commas (,) between the two arguments. Second, the format string you use must match the format of the dates you have.
Also, note the result of subtracting two datetime objects is a timedelta object. If you just want to print out the number 16, you'll need to extract the days property of the result:
a = datetime.strptime(date_string, '%Y-%m-%d')
b = datetime.strptime(prev_date_string, '%Y-%m-%d')
c = a-b
print (c.days)

The simple answer for this problem.
from datetime import date
a = date(2021, 5, 11)
b = date(2021, 5, 27)
c = b - a
print(c.days)

Related

Python strptime errors on parsing strftime output

I am trying to store a date in a human readable format. For that I save and read back a string containing a date. I am using date.min to denote a date before any other.
from datetime import datetime, date
d = date.min
s = datetime.strftime(d, "%Y-%m-%d")
print(s)
# 1-01-01
d2 = datetime.strptime(s, "%Y-%m-%d")
# ValueError: time data '1-01-01' does not match format '%Y-%m-%d'
However, when I try to parse the date using strptime that was output by strftime, I only get an error. It seems that strptime is expecting leading zeros like 0001, which strftime is not outputting.
It might be possible to use None. Are there any other ways to work around what seems like a bug to me?
You need to add leading zeros:
try replacing:
s = {datetime.strftime(d, "%Y-%m-%d")}
with:
s = f'{d.year:04d}-{datetime.strftime(d, "%m-%d")}'
If you want to work with dates easily, I can really suggest the 'Arrow' library.
https://pypi.org/project/arrow/
Python 3.9 on Linux exhibits the problem as expected in the many comments on the question. One workaround that should work on all platforms is to use ISO format for the date string with date.isoformat():
>>> from datetime import date, datetime
>>> s = date.min.isoformat()
>>> s
'0001-01-01'
>>> d = datetime.strptime(s, "%Y-%m-%d")
>>> d
datetime.datetime(1, 1, 1, 0, 0)
>>> assert d.date() == date.min
You can also use date.fromisoformat() instead of strptime():
>>> date.fromisoformat(date.min.isoformat())
datetime.date(1, 1, 1)
The strftime can't add leading zeros to the year. It calls the underlying C function and its behavior on adding leading zeros to the year is platform specific. You can work around this by formatting the date object by yourself. Just do a check if d.year is less than 1000 and add how many leading zeros needed:
d = date.min
year_str = ''.join(['0' for _ in range(4 - len(str(d.year)))]) + str(d.year)
s = '{year}-{md}'.format(year=year_str, md=datetime.strftime(d, "%m-%d"))
d2 = datetime.strptime(s, "%Y-%m-%d")
# now d2 is equal to datetime.datetime(1, 1, 1, 0, 0)

How to extract the month or number before the first / in a date?

I'm trying to do something like
date = "9/26/2017"
for %m in date:
%m = i
print(format(i, '02d'))
Is there a way to get the month number so that I can put a 0 in front of it?
I'm trying to take 9/26/2017 and output 09/26/2017.
from datetime import *
d = '9/26/2017'
d = datetime.strptime(d,'%m/%d/%Y').date()
d = datetime.strftime(d,'%m/%d/%Y')
print d
09/26/2017
you can split and zero-pad all fields in one line using format and unpacking arguments from conversion to integer of your splitted string:
"{:02}/{:02}/{:04}".format(*map(int,date.split("/")))
note: for only the first number, you could have used date.zfill(10) or to apply zfill on all terms with varying sizes:
"/".join(a.zfill(b) for a,b in zip(date.split("/"),[2,2,4]))
If you r reading date in the format you mentioned, then use
date = "9/26/2017"
d = date.split("/")
if len(d[0])==1:
date="0"+date
print(date)

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)

Calculating the time difference between two datetime values in Python

I want to compare two date and times with each other and then use that information for other stuff. Like if delta > 23 hours do this, elif delta > 11 hours, do that etc. I thought this would be a reasonable way to write it, but python won't accept it! It says:
ValueError: 'h' is a bad directive in format '%m/%d/%Y%h:%m:%s'
Isn't h the standard way to write hours in Python? :o
My dates are written in this format: "12/28/13 16:49:19", "m/d/y h:m:s" if that's any help!
from datetime import datetime
date_format = "%m/%d/%Y%h:%m:%s"
then=(dictionary["date"])
now= time.strftime("%c")
a = datetime.strptime(str(then), date_format)
b = datetime.strptime(str(now), date_format)
delta = b - a
print(delta.hour)
The 24 hour format is %H, a capital H, not a lowercase. The same for the minutes and seconds. You'll need a space as well, and you have a year format without the century, so use lower-case y:
date_format = "%m/%d/%y %H:%M:%S"
See the strftime() and strptime() behaviour documentation. %h doesn't exist as a format character.
And instead of using time.strftime('%c') to represent now, then parse that again, use:
b = datetime.now()
datetime.timedelta objects do not have an hours attribute; calculate the hours from the total seconds in the delta:
delta = b - a
print(delta.total_seconds() // 60)
or compare the delta object against another timedelta():
if delta > timedelta(hours=23):
Demo:
>>> from datetime import datetime
>>> date_format = "%m/%d/%y %H:%M:%S"
>>> datetime.strptime('12/28/13 16:49:19', date_format)
datetime.datetime(2013, 12, 28, 16, 49, 19)

Convert strange date format to standard date format

In Sweden we sometimes use a strange date format, for example New Year is the 31/12. If I have this format as a string ,which can be any date between 1/1 and 31/12, and if we assume that it is this year, how do I get into a standard date format using Python (format as 2012-01-01 and 2012-12-31) that can be sore in be stored as a date in a mySQL database.
Simply split the two values, map them to integers and update a datetime.date() instance:
import datetime
day, month = map(int, yourvalue.split('/'))
adate = datetime.date.today().replace(month=month, day=day)
By using datetime.date.today() we get the current year.
Demo:
>>> import datetime
>>> somevalue = '31/12'
>>> day, month = map(int, somevalue.split('/'))
>>> datetime.date.today().replace(month=month, day=day)
datetime.date(2012, 12, 31)
>>> someothervalue = '1/1'
>>> day, month = map(int, someothervalue.split('/'))
>>> datetime.date.today().replace(month=month, day=day)
datetime.date(2012, 1, 1)
Alternatively, you could use the datetime.strptime() method to parse these dates, but you'll have to manually correct the year afterwards (it'll use 1900 as the default if no year is being parsed):
adate = datetime.datetime.strptime(yourvalue, '%d/%m').date()
adate = adate.replace(year=datetime.date.today().year)
There is nothing strange about this format :)
You can use the datetime module:
import datetime
d = datetime.datetime.strptime('31/12', '%d/%m').date().replace(year=2012)
print d
>> datetime.date(2012, 12, 31)

Categories