Why is my date in python wrong after formating using timedelta? - python

I am using Django and have a problem with a date that I need to calculate.
The Variable data > test should be 17:00 and not 15:00. Why does this happen as soon as I format the date?
My timezone is Europe/Berlin. Changing the timezone has to effect to the time printing in test. It is always -2h
def date(req):
now = timezone.now()
model = MyModel.objects.filter(date__gt=now).first()
next = model.date
future = timezone.timedelta(hours=float(model.future)) #model.future = 1.5
open = next-future
date = next.strftime('%Y/%m/%d')
data = {
'next': next,
'date': date,
'time': open.astimezone(timezone.utc).strftime('%Y-%m-%d %H:%M:%S.%f'),
'test': open.strftime('%Y/%m/%d %H:%M:%S%z')
}
What I get:
next: 20. November 2021 18:30
date: 2021/11/20
time: 2021-11-20 15:15:00.000000
test: 2021/11/20 15:00:00+0000

https://docs.djangoproject.com/en/3.2/topics/i18n/timezones/#naive-and-aware-datetime-objects
You should use:
from django.utils import timezone
now = timezone.now()
Datetime isn't time-zone aware.

You cut the timezone info (the offset +02:00) with .strftime(). You need to include it with %z.
In case you want to convert it to a time string with the offset already added.
open.astimezone(timezone.utc).strftime('%Y-%m-%d %H:%M:%S.%f')

This works for me.
from django.utils import timezone
def date(req):
now = timezone.now()
model = MyModel.objects.filter(date__gt=now).first()
next = model.date
future = timezone.timedelta(hours=float(model.future)) #model.future = 1.5
open = next-future
date = timezone.localtime(open)
data = {
'next': date.strftime('%Y/%m/%d %H:%M:%S'),
'date': date.strftime('%Y/%m/%d'),
'time': date.strftime('%H:%M:%S'),
}

Related

How to add a 1 day to today's date in python?

What i'm trying to do is to add one extra day to today's date and have the outcome match this formula "%Y-%m-%d" and nothing else. I want the printed results to match this yyyy-mm-dd
from datetime import datetime, timedelta, date
s = date.today()
date = datetime.strptime(s, "%Y-%m-%d")
modified_date = date + timedelta(days=1)
datetime.strftime(modified_date, "%Y-%m-%d")
print(modified_date)
You are trying to do date operations on strings and not using the result of your formatting call:
s = date.today()
modified_date = s + timedelta(days=1)
modified_date = modified_date.strftime("%Y-%m-%d") # this would be more common
# modified_date = datetime.strftime(modified_date, "%Y-%m-%d")
print(modified_date)

Timestamp is different in flutter from Firestore and Postman

In my app, when the user adds a document, I store the timestamp of the document creation.
My app calls an api written in Flask.
I store the timestamp in python with:
timestamp = firestore.SERVER_TIMESTAMP
The timestamp is stored in Firestore as:
When the user requests the document, I process the timestamp to be shown in a readable way with the following code:
def get_proper_timestamp(timestamp) -> str:
if not timestamp:
return None
date: datetime.date = timestamp.date()
day = str(date.day)
month = str(date.month)
year = str(date.year)
if len(month) == 1:
month = f"0{month}"
proper_date = f"{day} {month} {year}"
weekday: int = date.weekday()
proper_weekday: str = get_day_from_int(weekday)
time = timestamp.time()
hour = time.hour
minute = time.minute
temp = strptime(f"{hour}:{minute}", "%H:%M")
proper_time: str = strftime("%I:%M %p", temp)
return f"{proper_weekday}, {proper_date}.{proper_time}"
def get_day_from_int(integer: int) -> str:
mapper = {
0: "Mon",
1: "Tues",
2: "Wed",
3: "Thur",
4: "Fri",
5: "Sat",
6: "Sun",
}
return mapper[integer]
In Postman, this outputs:
My flutter code reads the timestamp in a straight-forward way:
List<DataCell> _buildCells(Map<String, dynamic> entry) {
String timestamp = entry["timestamp"];
print(timestamp);
return [
DataCell(Text(entry["timestamp"].toString())),
DataCell(Text(entry["amount"].toString())),
DataCell(Text(entry["after"].toString()))
];
}
This outputs:
This is four hours before. Which I think it means that I'm the UTF offset somewhere.
But why is Postman showing the date correctly?
I'd actually prefer flask to return the raw timestamp, but I couldn't deserialize it.
I read most the answers on SO on this issue, but nothing worked for me.
The value stored in Firestore is an internal structure, which is timezone agnostic (internally based on UTC).
The value you see in the Firestore console has been localized to your local timezone for your convenience, which is apparently UTC+4.
The value you get when fetching the time with Flutter is a Timestamp, also UTC-based and timezone agnostic. When you convert that with .toDate() (or the equivalent with millisecondsSinceEpoch), it becomes a traditional DateTime, which is internally in UTC, but carries a localtime offset, and normally displays itself as localtime. This is probably the value you are seeing as +4.

How can I get only the hour or minute part from post request in Django?

I want to receive only the hour part or minute part in django. Right now i'm using remindTime = request.POST.get("remindTime") to get the time but I only want the hour or minute or day or month. How can I do that?
here is the model
class Reminder(models.Model):
remindTime = models.DateTimeField(auto_now_add=False, auto_now=False)
how I get the time
if request.method == "POST":
remindTime = request.POST.get("remindTime")
Ty!
First, convert your string object to Datetime object:
my_string = '2019-10-31'
# Create date object in given time format yyyy-mm-dd
my_date = datetime.strptime(my_string, "%Y-%m-%d")
print(my_date)
print('Type: ',type(my_date))
Output:
2019-10-31 00:00:00 Type:
Second, step get your hour and minute:
print('Month: ', my_date.month) # To Get month from date
print('Year: ', my_date.year) # To Get month from year
Output:
Month: 10 Year: 2019

How to calculate the number of days remaining for another date

How to import a date from view and calculate the number of days remaining for another date?
Here is the solution I tried but it's not working:
class saisir_soumi(osv.osv):
_name='saisir.soumi'
def compa_date(self,cr,uid,ids,args,fields,context=None):
r = {}
date_format = "%D/%M/%Y"
joining_date = 'date_depot'
current_date = '29/04/2016 02:02:02'# current date
d1 = datetime.strptime(joining_date, date_format)
d2 = datetime.strptime(current_date, date_format)
diff = current_date - datetime.date.today()
return diff.days
_rec_name = 'NumOffre'
_columns = {
'NumOffre' : fields.char('N° Offre',required=True),
'organisme_s' : fields.char('Organisme',required=True),
'date_depot' : fields.datetime('Date dépot de soumission'), # the date to be seized and used for its difference with current date( today)
'jrestant': fields.function(compa_date,string='Jours restant')
}
_sql_constraints = [
('uniq_NumOffre', 'unique(NumOffre,id)', "numero offre doit resté unique !"),
]
you have to do it properly:
specify correct date/time format
parse datetime from string
substract the same data types: datetime - datetime
Code:
In [68]: current_date = '29/04/2016 02:02:02'
In [69]: date_format = '%d/%m/%Y %H:%M:%S'
In [70]: (datetime.datetime.strptime(current_date, date_format) - datetime.datetime.now()).days
Out[70]: 5

Date filter in Django model results unexpected behavior

It seems to be easy but it creates confusion for me. My code is
today = datetime.datetime.now()
StatusObj = Status.objects.filter(taskPeople__people__email = useremail,dateCreated__year = today.year, dateCreated__month = today.month, dateCreated__day = today.day)
it is expected that it will filter the query whose date is today. But it doesn't filter instead it filter one day back query.
when I do.
today.day
>> 20
Status.objects.filter(taskPeople__people__email = useremail,dateCreated__year = today.year, dateCreated__month = today.month, dateCreated__day = today.day)[0].dateCreated.day
>>19
You should use django.utils.timezone.now instead of datetime.datetime.now.
from django.utils import timezone
today = timezone.now()
...
Read the question #3 in the troubleshooting section of the timezones docs.

Categories

Resources