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;
Related
I have a dictionary which has a timestamp stored as key and value pairs:
timestamp_info = {
'day': 8, 'fold': 0, 'hour': 0,
'max': {'day': 31, 'fold': 0,'hour': 23},
'microsecond': 639000, 'minute': 17, 'month': 10, 'second': 35, 'year': 2021
}
I am trying to take timestamp from dictionary and convert to datetime.datetime timestamp format. I tried the following but it does not work as it asks for str (exact error is: "strptime() argument 1 must be str, not dict"):
result = datetime.datetime.strptime(timestamp_info, "%Y-%m-%d %H:%M:%S")
I want this result to be compared with datetime.datetime.now and take difference in seconds between current timestamp and result, that is the reason I need timestamp format.
Chirs Oram already shows how to build a string that you can then parse with strptime(). Alternatively, you can pass the values directly to datetime():
timestamp_info = {
'day':8, 'fold':0,'hour':0, 'max':{'day':31, 'fold':0,'hour':23},
'microsecond':639000,'minute':17,'month':10,'second':35, 'year':2021
}
year = timestamp_info['year']
month = timestamp_info['month']
day = timestamp_info['day']
hour = timestamp_info['hour']
minute = timestamp_info['minute']
second = timestamp_info['second']
result = datetime.datetime(year=year, month=month, day=day, hour=hour, minute=minute, second=second)
Or you can do this more succinctly by removing the attributes not needed for datetime:
timestamp_info = {
'day':8, 'fold':0,'hour':0, 'max':{'day':31, 'fold':0,'hour':23},
'microsecond':639000,'minute':17,'month':10,'second':35, 'year':2021
}
del timestamp_info['fold']
del timestamp_info['max']
result = datetime.datetime(**timestamp_info)
You can extract each part of the timestamp in the specified format, and concatenate them into a string:
timestamp_info = {
'day':8, 'fold':0,'hour':0, 'max':{'day':31, 'fold':0,'hour':23},
'microsecond':639000,'minute':17,'month':10,'second':35, 'year':2021
}
year = str(timestamp_info['year'])
month = str(timestamp_info['month'])
day = str(timestamp_info['day'])
hour = str(timestamp_info['hour'])
minute = str(timestamp_info['minute'])
second = str(timestamp_info['second'])
timestamp = '-'.join([year, month, day]) + ' ' + ':'.join([hour, minute, second])
result = datetime.datetime.strptime(timestamp, "%Y-%m-%d %H:%M:%S")
Which results in:
2021-10-08 00:17:35
I'm trying to replace the day in my if statement for my date but I keep getting this output for my year.
05/15/5 besides 05/15/2020 . Code is below:
today_date = datetime.datetime.now()
date = today_date.date()
formatted_date = datetime.date.strftime(date, "%m/%d/%Y")
mmonth = date.month
myear = date.year
mdate = date.day
if mdate < 7:
m0weekend = formatted_date.replace(str(myear),str(mmonth),1)
else:
m0weekend = formatted_date.replace(str(myear),str(mmonth),15)
it's easier to replace the day before converting to a string:
date = date.replace(day=1)
or, in your case:
if mdate < 7:
m0weekend = date.replace(day=1)
else:
m0weekend = date.replace(day=15)
formatted_date is actually a string.
You are using the str.replace() method not the datetime.date.replace() method.
import datetime
today_date = datetime.datetime.now()
pre_formatted_date = today_date.date()
mmonth = pre_formatted_date.month
myear = pre_formatted_date.year
mdate = pre_formatted_date.day
if mdate < 7:
pre_formatted_date = pre_formatted_date.replace(day=1)
else:
pre_formatted_date = pre_formatted_date.replace(day=15)
print(pre_formatted_date)
formatted_date = pre_formatted_date.strftime("%m/%d/%Y")
print(formatted_date)
Which has the following output:
2020-05-15
05/15/2020
You might get today datetime.date directly from datetime rather than creating datetime.datetime and converting to date. After you have today you might create needed datetime.date and turn it into str, i.e.:
import datetime
today = datetime.date.today()
date = datetime.date(today.year, today.month, 1 if today.day < 7 else 15)
formatted_date = datetime.date.strftime(date, "%m/%d/%Y")
print(formatted_date) # 05/15/2020
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)
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())
model:
class MyClass(models.Model):
car = models.ForeignKey(Car)
date = models.DateTimeField(auto_now=True, auto_now_add=True)
sql:
SELECT car FROM cars_myclass WHERE date < NOW() - INTERVAL 1 DAY;
So, I have something like:
cars = MyClass.objects.all().filter(date < ... )
But how to write NOW() - INTERVAL 1 DAY ? Thanks.
Pass datetime.datetime object (substracted by datetime.timedelta object):
>>> import datetime
>>> now = datetime.datetime.now()
>>> now
datetime.datetime(2013, 12, 29, 21, 54, 30, 836000)
>>> now - datetime.timedelta(days=1)
datetime.datetime(2013, 12, 28, 21, 54, 30, 836000)
import datetime
cars = MyClass.objects.filter(date__lt=datetime.datetime.now() - datetime.timedelta(days=1))
UPDATE Comment by Mikko Ohtamaa:
Also to avoid problems with timezones I recommend using timezone.now() instead of datetime.datetime.now() (available since Django 1.4)
import datetime
from django.utils import timezone
cars = MyClass.objects.filter(date__lt=timezone.now() - datetime.timedelta(days=1))