user8817894
user8817894

Reputation:

Sort weekdays from datetime objects

I want to get the weekdays for every similar week from a list of datetime objects.

Example: For the list [2020-08-17 07:00:00, 2020-08-28 05:00:00, 2020-08-17 09:00:00, 2020-08-18 09:00:00, 2020-08-24 02:00:00, 2020-08-27 02:00:00]

The result should be as :

list_1 = ['Mon', 'Tue']
list_2 = ['Mon', 'Thu', 'Fri']

Upvotes: 1

Views: 290

Answers (3)

DenverCoder1
DenverCoder1

Reputation: 2501

from datetime import datetime, timedelta
from collections import defaultdict

dates = ["2020-08-17 07:00:00", "2020-08-28 05:00:00", "2020-08-17 09:00:00", "2020-08-18 09:00:00", "2020-08-24 02:00:00", "2020-08-27 02:00:00"]

weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']

# create a dictionary for storing each week's list
# default value for each entry is an empty list
weeks = defaultdict(list)

for dateString in dates:
  # create datetime object from list element
  date = datetime.strptime(dateString, '%Y-%m-%d %H:%M:%S')
  # get the weekday of the date
  weekday = weekdays[date.weekday()]
  # get the date of last Monday (for indexing weeks)
  weekMonday = (date - timedelta(days=date.weekday())).strftime("%Y-%m-%d")
  # add weekday to the corresponding week entry in the dict
  weeks[weekMonday].append(weekday)
  # sort and remove duplicates
  weeks[weekMonday] = list(sorted(set(weeks[weekMonday]), key=lambda x: weekdays.index(x)))

# print results
for x in weeks:
  print("Week of " + x + ":", weeks[x])

Output:

Week of 2020-08-17: ['Mon', 'Tue']
Week of 2020-08-24: ['Mon', 'Thu', 'Fri']

You can access each list by giving the date of that week's Monday, for example:

print(weeks["2020-08-17"])  # ['Mon', 'Tue']

Upvotes: 1

hhaefliger
hhaefliger

Reputation: 531

This will convert the dates to days of the week (0-6):

import datetime

dates = ['2020-08-17 07:00:00', '2020-08-17 09:00:00', '2020-08-18 09:00:00', '2020-08-24 02:00:00', '2020-08-27 02:00:00', '2020-08-28 05:00:00']

dates = [datetime.datetime(int(item[0:4]), int(item[5:7]), int(item[8:9])) for item in dates]

days = [date.weekday() for date in dates]
weeks = [date.isocalendar()[1] for date in dates]

counts = {}

for i in range(len(days)):
    if weeks[i] in counts:
        if not(days[i] in counts[weeks[i]]):
            counts[weeks[i]].append(days[i])

    else:
        counts[weeks[i]] = [days[i]]

Upvotes: 0

Aviv Yaniv
Aviv Yaniv

Reputation: 6298

Utilize a dictionary to efficiently track of the days in week:

from dateutil import parser

# The given dates as strings
sabich = [ '2020-08-17 07:00:00' , '2020-08-28 05:00:00' , '2020-08-17 09:00:00' , '2020-08-18 09:00:00' , '2020-08-24 02:00:00' , '2020-08-27 02:00:00' ]

weeks_dates = dict()

# Loop on the given dates as strings
for ds in sabich:
    # Parse date from string o datetime object
    dt = parser.parse(ds)
    # Find date's week in year
    week_in_year = dt.isocalendar()[1]
    # Find date's day in week name
    date_day_name = dt.strftime("%A")
    # If week doesn't exists as key (no days of that date existed)
    if week_in_year not in weeks_dates.keys():
        # Create list to add the date names to that list
        weeks_dates[week_in_year] = []
    # Append the date week day name
    weeks_dates[week_in_year].append(date_day_name)

# Printing the days names for each week
for week_in_year in weeks_dates.keys():
    print(f'Week number {week_in_year}, days that appeared {weeks_dates[week_in_year]}')

Output:

Week number 34, days that appeared ['Monday', 'Monday', 'Tuesday']
Week number 35, days that appeared ['Friday', 'Monday', 'Thursday']

Upvotes: 0

Related Questions