Difference between two timestamps with different weekdays? - python

I've the following dates:
Tue 19:00-20:00
Wed 04:25-15:14
How can i get the difference between Tue 20:00 and Wed 04:25?
I've tried to transform it in datetime objects but since i don't have the day of the month or a year both objects will get the same date:
d1 = datetime.strptime("Tue 20:00", "%a %H:%M")
d2 = datetime.strptime("Wed 04:25", "%a %H:%M")
d1 is: datetime.datetime(1900, 1, 1, 20, 0)
d2 is: datetime.datetime(1900, 1, 1, 4, 25)
The difference in minutes should be 505 but in this case will be -935.0 because they have the same date, and so they differ by almost 16 hours and not about 8 and a half:
diff = (d2 - d1).total_seconds() / 60 # -935.0

datetime.strptime() can't do anything else, because the day of the week is not enough to form a date. You'd need a week number and a year for a week-day to make any sense. If you need to get the relative difference between two dates that are assumed to be in the same week, then any week number and year would do, e.g.:
arbitrary_iso_week = "2020-25 "
d1 = datetime.strptime(arbitrary_iso_week + "Tue 20:00", "%G-%V %a %H:%M")
d2 = datetime.strptime(arbitrary_iso_week + "Wed 04:25", "%G-%V %a %H:%M")
This makes use of the %G and %V formatters for ISO 8601 week numbers.
This produces datetime objects with a more meaningful date releationship:
>>> arbitrary_iso_week = "2020-25 "
>>> d1 = datetime.strptime(arbitrary_iso_week + "Tue 20:00", "%G-%V %a %H:%M")
>>> d2 = datetime.strptime(arbitrary_iso_week + "Wed 04:25", "%G-%V %a %H:%M")
>>> d1
datetime.datetime(2020, 6, 16, 20, 0)
>>> d2
datetime.datetime(2020, 6, 17, 4, 25)
>>> (d2 - d1).total_seconds() / 60
505.0
The actual dates don't matter here, just their difference in days. d1 is now earlier, not later, than d2.
You may have to take into account that week days are circular, in that you could have an earlier date on, say, Friday, and a later date on Monday. If you can assume that the first value must be earlier than the second, then the solution is simple. Just subtract 7 days from d1 if it is later than d2:
# if the first date must come before the second, then it must be one week earlier.
if d1 > d2:
d1 -= timedelta(days=7)

Related

python strptime ignoring %A?

I have some arbitrary-week times in the following format: "Monday 11:30am"
I would like to parse these into datetime.datetimes. I don't care what year/month/day I end up with in the object, but if the string says "Monday", then the resulting datetime.datetime should be a day that is a Monday.
Unfortunately, the %A formatter (day of week) seems to be ignored by strptime:
>>> import datetime
>>> a = "Monday 11:30am"
>>> b = "Tuesday 11:30am"
>>> dt_format = "%A %I:%M%p"
>>> datetime.datetime.strptime(a, dt_format)
datetime.datetime(1900, 1, 1, 11, 30)
>>> datetime.datetime.strptime(b, dt_format)
datetime.datetime(1900, 1, 1, 11, 30)
How do I correctly parse the day of the week?
It seems that datetime is not picking up a date correctly when only specifying the day of the week.
Since you do not care what year/month/day you end up with, you can use the current week number of the year. When combined with the day and week number, datetime will output a date correctly.
import datetime
import calendar
rand_date = datetime.datetime.strftime(datetime.datetime.today(), '%U %Y ')
dt_format = "%U %Y %A %I:%M%p"
a = "Monday 11:30am"
b = "Tuesday 11:30am"
print(datetime.datetime.strptime(rand_date + a, dt_format))
print(calendar.day_name[datetime.datetime.strptime(rand_date + a, dt_format).weekday()])
print(datetime.datetime.strptime(rand_date + b, dt_format))
print(calendar.day_name[datetime.datetime.strptime(rand_date + b, dt_format).weekday()])
2021-02-22 11:30:00
Monday
2021-02-23 11:30:00
Tuesday

convert element and next element in list of strings to date in python

I am new to Python and am having trouble with the following string:
Order now for free delivery loose on Tuesday, April 25 or set in
jewelry on Tuesday, April 29.
I have converted it to a list of strings with .split(). However, I cannot figure out how to iterate through the list to pull out the dates such as April 25 and April 29. Once I pull these strings out, I know I can convert them to a date format with datetime.strptime(string, '%B %d') with string being "April 25" and "April 29" and can apply a date-diff function.
I think I need to pull both list elements that contain month names as strings and the next element with the day of the month to combine them in order to convert them to date format.
Any assistance would be much appreciated. Thank you in advance.
Praise the power of regular expressions here:
import re
from datetime import datetime
s = "Order now for free delivery loose on Tuesday, April 25 or set in jewelry on Tuesday, April 29."
# regex looking for dates in the given format
rx = re.compile(r'''
(?:(?:Mon|Tues|Wednes|Thurs|Fri|Satur|Sun)day),\s+
(?:January|February|March|April|May|June|July|August|September|October|November|December)\s+
\d+
''', re.VERBOSE)
dates = [datetime.strptime("{} #{}".format(m.group(0), "2017"), '%A, %B %d #%Y')
for m in rx.finditer(s)]
print(dates)
# [datetime.datetime(2017, 4, 25, 0, 0), datetime.datetime(2017, 4, 29, 0, 0)]
If it's intended for the current 2017 year, the solution using calendar.day_name (the days of the week), calendar.month_name (the months of the year) and datetime.strptime() function:
import calendar, datetime
s = 'Order now for free delivery loose on Tuesday, April 25 or set in jewelry on Tuesday, April 29'
day_names = '|'.join(list(calendar.day_name)) # Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday
month_names = '|'.join(list(calendar.month_name[1:]))
dates = re.findall(r'((' + day_names + '), (' + month_names + ') \d{1,2})', s)
datetimes = [datetime.datetime.strptime(d[0] + ' 2017', '%A, %B %d %Y') for d in dates]
print(datetimes)
The output:
[datetime.datetime(2017, 4, 25, 0, 0), datetime.datetime(2017, 4, 29, 0, 0)]

Split and Combine Date

I am trying to write a python script that will compare dates from two different pages. The format of date in one page is Oct 03 2016 whereas on other page is (10/3/2016). My goal is to compare these two dates. I was able to convert Oct to 10 but don't know how to make it 10/3/2016.
You should really be using the dateutil library for this.
>>> import dateutil.parser
>>> first_date = dateutil.parser.parse('Oct 03 2016')
>>> second_date = dateutil.parser.parse('10/3/2016')
>>> first_date
datetime.datetime(2016, 10, 3, 0, 0)
>>> second_date
datetime.datetime(2016, 10, 3, 0, 0)
>>> first_date == second_date
True
>>>
Use datetime module to convert your string to datetime object and then compare both. For example:
>>> from datetime import datetime
>>> date1 = datetime.strptime('Oct 03 2016', '%b %d %Y')
>>> date2 = datetime.strptime('10/3/2016', '%m/%d/%Y')
>>> date1 == date2
True
Further, you may convert thisdatetime object to your custom format using datetime.strftime() as:
>>> date1.strftime('%d * %B * %Y')
'03 * October * 2016'
List of all the directives usable for formatting the string are available at the strftime link I mentioned above.

How to convert 2015 June 1 into date format in python [duplicate]

This question already has answers here:
Convert string date into date format in python?
(3 answers)
Closed 7 years ago.
How to convert 2015 June 1 into date format in python like date_object = datetime.date(2014, 12, 4)
You can use the format - '%Y %B %d' along with datetime.datetime.strptime() method to convert string to date. Where %Y is 4 digit year, %B is complete month name, and %d is date.
Example/Demo -
>>> datetime.datetime.strptime('2015 June 1','%Y %B %d')
datetime.datetime(2015, 6, 1, 0, 0)
>>> datetime.datetime.strptime('2015 June 1','%Y %B %d').date()
datetime.date(2015, 6, 1)
Use the first one, if you are content with datetime object, if you want the date() object itself, you can use the second one.
You can use the date constructor
>>> from datetime import date
>>> date_object = date(year=2015, month=6, day=1)
>>> print date_object
2015-06-01

How to get week start dates and week number of each week in a year considering start day of the week is Monday in python?

How can I get week start dates of each week in a year, considering start day of the week is Monday in python?
This assumes start day is Sunday:
>>>import datetime as datetime
>>>dt = datetime .date(2013,12,30)
>>>dt.isocalendar()[1]
1
However, result shouldn't be 1, because 30-12-2013 is still in 2013.
I don't think behaviour of isocalendar can be changed.
From : http://docs.python.org/2/library/datetime.html#datetime.date.isocalendar
The first week of an ISO year is the first (Gregorian) calendar week of a year containing a Thursday.
But strftime can display week number :
%U "All days in a new year preceding the first Sunday are considered to be in week 0."
%W "All days in a new year preceding the first Monday are considered to be in week 0."
>>> import datetime
>>> dt = datetime.date(2013,12,30)
>>> dt.isocalendar()
(2014, 1, 1)
>>> dt.strftime("%U")
'52'
But to respond to your first question, why don't you just use datetime.timedelta ?
>>> import datetime
>>> dt = datetime.date(2013,12,30)
>>> w = datetime.timedelta(weeks=1)
>>> dt - w
datetime.date(2013, 12, 23)
>>> dt + w
datetime.date(2014, 1, 6)
>>> dt + 10 * w
datetime.date(2014, 3, 10)

Categories

Resources