How to convert a string of dates to a date object? - python

I'm doing a chatbot to book rooms. I've created a function to check if the room asked is free while looking in the database. At some point I try to convert the entry starting and ending meeting hour to a tupple with from_pendulum_to_tupple(day_startinghour) with day_startinghour beeing for instance 2019-04-18T14:00:00+00:00
def from_pendulum_to_tupple(date):
print("date: ")
print(date)
print("type : " + str(type(date)))
year = date.year
month = date.month
day = date.day
hour = date.hour
minute = date.minute
return (year, month, day, hour, minute)
Yet I have an AttributeError: str object has no attribute year. Indeed, the error message is:
File
"C:\Users\antoi\Documents\Programming\Nathalie\18_2_2019\starter-pack-rasa-stack\actions.py",
line 43, in run
booking_answer = make_a_booking(name_room, day, hour_start, duration)
File "C:\Users\antoi\Documents\Programming\Nathalie\18_2_2019\starter-pack-rasa-stack\booking.py",
line 94, in make_a_booking
room_available = is_the_room_available(name_room, day_only, pendulum_combined_day_and_hour_start,
pendulum_combined_day_and_hour_end, cnx)
File "C:\Users\antoi\Documents\Programming\Nathalie\18_2_2019\starter-pack-rasa-stack\booking.py",
line 52, in
is_the_room_available
starting_hour_list.append(from_pendulum_to_tupple(start_time))
File "C:\Users\antoi\Documents\Programming\Nathalie\18_2_2019\starter-pack-rasa-stack\booking.py",
line 14, in
from_pendulum_to_tupple
year = date.year
AttributeError: 'str' object has no attribute 'year'
127.0.0.1 - - [2019-04-17 16:42:01] "POST /webhook HTTP/1.1" 500 412 1.050171
day_startinghour was created with make_a_booking which takes room, a day and an hour before calling for the above function to know if the room is used on the times we want to book it:
def make_a_booking(name_room, day, hour_start, duration):
print(name_room, day, hour_start, duration)
# connect to the localhost database
cnx = mysql.connector.connect(password='MySQL.2019', user="root", database="alex")
#day_only : get the parsed date
day_only = str(dateparser.parse(day).date())
# parse the hour in string inputed by the user and convert it the a pendulum object
hour_start_parsed = dateutil.parser.parse(hour_start, fuzzy_with_tokens=True)
pendulum_combined_day_and_hour_start = pendulum.parse(str(day_only) + " " + hour_start, strict=False)
# convert the duration in string inputed by the user and to seconds then in minutes
duration_in_seconds = convert_time(duration)
duration_in_minutes = duration_in_seconds / 60
# add the duration_in_minutes to the starting hour to get the hour start pendulum object
pendulum_combined_day_and_hour_end = pendulum_combined_day_and_hour_start.add(minutes = duration_in_minutes)
#print(pendulum_combined_day_and_hour_end)
# check if the room is available
room_available = is_the_room_available(name_room, day_only, pendulum_combined_day_and_hour_start, pendulum_combined_day_and_hour_end, cnx)

Using dparser:
import dateutil.parser as dparser
def from_pendulum_to_tupple(date):
print("date: {}".format(date))
date = dparser.parse(date,fuzzy=True)
year = date.year
month = date.month
day = date.day
hour = date.hour
minute = date.minute
return (year, month, day, hour, minute)
s = '2019-04-18T14:00:00+00:00'
print(from_pendulum_to_tupple(s))
OUTPUT:
date: 2019-04-18T14:00:00+00:00
(2019, 4, 18, 14, 0)

Related

Time of Day Calculation Python

I have a script that downloads files from a site each day. There is one file per day and a new file is added 16:00. The file names use year, month date in title of file so I use that to know which files to get.
I am trying write in my script that if the current time today is before 4pm then find:
year = 2020
month = 4
day = 15
But if it is past 4pm then find:
year = 2020
month = 4
day = 16
I have tried:
timerightnow = datetime.now()
today4pm = timerightnow.replace(hour=16, minute=0, second=0, microsecond=0)
But then doing timerightnow < today4pm gives me a syntax error?
Any ideas would be great!
Thanks
For those wondering the solution:
timerightnow = datetime.now()
today4pm = timerightnow.replace(hour=16, minute=0, second=0, microsecond=0)
if timerightnow < today4pm:
year = timerightnow.year
month = timerightnow.month
day = timerightnow.day -1
else:
year = timerightnow.year
month = timerightnow.month
day = timerightnow.day

Strftime error Python

I'm calling a function to get the calculation for driver revenue but, I keep getting this error:
"line 396, in driver_get_revenue
monthly[month.strftime("%m")] = orders.count() * settings.DRIVER_DELIVERY_PRICE
AttributeError: 'int' object has no attribute 'strftime'"
The function is this:
def driver_get_revenue(request):
driver = JWTAuthentication().authenticate(request)[0].driver
#Returns the difference between date and time.
from datetime import timedelta
revenue = {}
monthly = {}
yearly = {}
today = timezone.now()
month = today.month
year = today.year
#Created a range to calculate the current weekday.
current_weekdays = [today + timedelta(days = i) for i in range(0 - today.weekday(), 7 - today.weekday())]
for day in current_weekdays:
orders = Order.objects.filter(
driver = driver,
status = Order.DELIVERED,
created_at__year = day.year,
created_at__month = day.month,
created_at__day = day.day
)
revenue[day.strftime("%A")] = orders.count() * settings.DRIVER_DELIVERY_PRICE
for day in range(0, 30):
orders = Order.objects.filter(
driver = driver,
status = Order.DELIVERED,
created_at__month = month,
created_at__day = day
)
(Line 396) monthly[month.strftime("%m")] = orders.count() * settings.DRIVER_DELIVERY_PRICE
for month in range(0, 12):
orders = Order.objects.filter(
driver = driver,
status = Order.DELIVERED,
created_at__year = year,
created_at__month = month
)
yearly[year.strftime("%y")] = orders.count() * settings.DRIVER_DELIVERY_PRICE
return JsonResponse({"revenue": revenue,
"month": monthly,
"yearly": yearly})
I'm not exactly sure where I went wrong. I marked line 396 so that you see where the error is. Any help will be greatly appreciated.
Thanks.
When you do this: month = today.month, month becomes an integer. The strftime function works with datetime objects, not with integers.
Therefore, month.strftime("%m") doesn't work.
Try day.strftime("%m") instead, or perhaps just month, depending on your requirements.
If instead you're looking for the month's name, you could do it like this:
today = timezone.now()
month = today.month
month_name = today.strftime("%B") # e.g. December
...
...and use the month_name variable in your code.

How to extract day, month and year from utcnow?

I have the following var: time_created = datetime.utcnow()
How to create a time_created_day var from time_created that will contain only Y, M, d
like this datetime.datetime(2017, 11, 7)
I have the following solution:
from datetime import date
time_created_day = date(time_created.year, time_created.month, time_created. day)
is it the best way?
Use datetime.utcnow().date()
datetime.utcnow().date()
datetime.date(2017, 11, 7)
Adding to answer
The datetime object always contains year, month, day as well as hours, minutes, seconds, and microseconds. It is a combination of what the date and time objects contain, see datetime Objects
from datetime import datetime
# this is your datetime object
time_created = datetime.utcnow()
# when you want to see it formatted as Y,M,D call the date method
date_created = time_created.date()
time_created
date_created
Output:
datetime.datetime(2017, 11, 7, 23, 43, 43, 761750)
datetime.date(2017, 11, 7)`
Use time_created.day to find the day.
time_created_day = time_created.day
(Similar for month and year)
here it is easiest for you
var dateObj = new Date();
var month = dateObj.getUTCMonth() + 1; //months from 1-12
var day = dateObj.getUTCDate();
var year = dateObj.getUTCFullYear();
newdate = year + " " + month + " " + day;

AttributeError: 'str' object has no attribute 'sleep'

I am getting AttributeError: 'str' object has no attribute 'sleep' as specified in the title of this question and I cannot figure out why it is throwing that error message.
Countdown Timer.py
import time, datetime
Year = 2020
Month = 12
Day = 24
Hour = 23
Minute = 18
Second = 50
while True:
Datetime = datetime.datetime(Year, Month, Day, Hour, Minute, Second)
diff = Datetime - datetime.datetime.now()
diff = str(diff)
days, not_useful, time = diff.split()
Day1 = days + " " + "Day" # Day
print(Day1)
time.sleep(1)
That's because you locally erased the variable time that contained the module with a string. Here is a correct code:
import time, datetime
Year = 2020
Month = 12
Day = 24
Hour = 23
Minute = 18
Second = 50
while True:
Datetime = datetime.datetime(Year, Month, Day, Hour, Minute, Second)
diff = Datetime - datetime.datetime.now()
diff = str(diff)
days, not_useful, time_str = diff.split()
Day1 = days + " " + "Day" # Day
print(Day1)
time.sleep(1)
days, not_useful, time = diff.split()
here you will have 'time' as string. change verb name...
It's because you are using Time as a variable in your code:
time = diff.split()
and the above line is locally overwriting the variable timein the time-module.
Try using a different variable:
time_1 = diff.split()

Django built-in timesince filter to show only Days

I am using {{ prospect.date_1 }} - ({{ prospect.date_1|timesince }} ago) in my template to get time since the date.
The point is, date_1 is a date not datetime, so when i apply the filter it tells me like
July 18, 2014 - (11 hours, 39 minutes ago)
expected output
July 18, 2014 - (0 days ago)
taken from naturalday
#register.filter(expects_localtime=True)
def days_since(value, arg=None):
try:
tzinfo = getattr(value, 'tzinfo', None)
value = date(value.year, value.month, value.day)
except AttributeError:
# Passed value wasn't a date object
return value
except ValueError:
# Date arguments out of range
return value
today = datetime.now(tzinfo).date()
delta = value - today
if abs(delta.days) == 1:
day_str = _("day")
else:
day_str = _("days")
if delta.days < 1:
fa_str = _("ago")
else:
fa_str = _("from now")
return "%s %s %s" % (abs(delta.days), day_str, fa_str)
results
>>> days_since(datetime.now())
'0 days ago'
>>> days_since(date(2013, 5, 12))
'432 days ago'
>>> days_since(date(2014, 12, 12))
'147 days from now'
>>> days_since(date(2014, 7, 19))
'1 day from now'
#Jack, Have you tried to use in-built python:
Visit: https://docs.python.org/2/library/datetime.html#datetime.datetime.day
Also if this might help:
https://docs.djangoproject.com/en/1.6/ref/contrib/humanize/#naturaltime
Edit:
from datetime import date
from datetime import datetime
d = date.today()
datetime.combine(d, datetime.min.time())

Categories