Andrius
Andrius

Reputation: 21118

Python construct datetime having weekday with other time parameters

I need to construct datetime object from different parameters. For example, I get these parameters:

And then I know which week of the current year it is going to be. So, for example, let say that datetime should be from 2014-07-18 00:00:00 to 2014-07-24 23:59:00 (seconds can be ignored and left at 00). So to get exact datetime I need to use above defined parameters.

Let say I would get these parameters 4 (meaning Friday), and 9.5 (meaning 09:30).

So by doing such construction, I should get a date that would be: 2014-07-22 09:30:00. How could accomplish such thing?

Do I need to somehow get for example day of the month by knowing which is the week of the year and which weekday it is?

P.S. A bit more detailed example of what I'm trying to accomplish

from datetime import datetime

today = datetime.today() #using this to get the week I'll be working with.

today = today.replace(day=?) #how to get which day I 
#need to enter by having weekday and knowing that week is the present one?

Upvotes: 3

Views: 7251

Answers (3)

danbeggan
danbeggan

Reputation: 105

I would use timedelta to add the difference between weekdays to the datetime

from datetime import datetime, timedelta

friday = 4

today = datetime.now()

friday_this_week = today + timedelta(friday - today.weekday())

In your case just replace today with a date that is in the week you want.

Upvotes: 1

axelcdv
axelcdv

Reputation: 753

You could do something like that, if your parameters are weekday and t (time):

from datetime import timedelta
monday = today - timedelta(days=today.weekday())
result = (monday + timedelta(days=weekday)).replace(hour=int(t), minutes=int((t - int(t)) * 60))

Upvotes: 3

Martijn Pieters
Martijn Pieters

Reputation: 1121486

If you have a starting date, use the relative value of the datetime.datetime.weekday() value to construct a timedelta() object that'll put you onto the right weekday, then replace the hour and minutes:

from datetime import timedelta

def relative_date(reference, weekday, timevalue):
    hour, minute = divmod(timevalue, 1)
    minute *= 60
    days = reference.weekday() - weekday
    return (reference - timedelta(days=days)).replace(
        hour=int(hour), minute=int(minute), second=0, microsecond=0)

Demo:

>>> from datetime import timedelta, datetime
>>> def relative_date(reference, weekday, timevalue):
...     hour, minute = divmod(timevalue, 1)
...     minute *= 60
...     days = reference.weekday() - weekday
...     return (reference - timedelta(days=days)).replace(
...         hour=int(hour), minute=int(minute), second=0, microsecond=0)
... 
>>> relative_date(datetime.now(), 4, 9.5)
datetime.datetime(2014, 8, 22, 9, 30)
>>> relative_date(datetime.now() - timedelta(days=30), 6, 11.75)
datetime.datetime(2014, 7, 27, 11, 45)

Upvotes: 1

Related Questions