Python - Recalculate current date - python

I have a python app running in a server (using flask) and i am having problems with the current date.
I have a method that calculates current date:
import time
def calcCurrent():
return(time.strftime("%d/%m/%Y"))
It works fine during this day, but, if I try to access to the server the day after and I call this method, it still returns the previous day date. It is, it doesn't recalculate current date.
Any idea on how could I do this?

try using this
import datetime
def calcCurrent():
return(datetime.datetime.now().strftime("%d/%m/%Y"))

Related

Flask/Dash application running as a service in windows must be restarted every day to include the current day's date. How to solve the problem?

I have this Flask/Dash application that I deployed as a service running in the background and it works fine. I use a datepicker (calendar) in the application to choose the date for which the data will be fetched and processed. However, the date of today is being grayed (deactivated) every day until I restart the service. I am using this :
from dash import dcc
dcc.DatePickerSingle(id='previ_date',
min_date_allowed=datetime.date(2022, 5, 10),
max_date_allowed=datetime.date.today(),
initial_visible_month=datetime.date.today(),
date=datetime.date.today())
Normally, the max_date_allowed argument is set to today's date, however, it doesn't behave as expected. Any help on how to overcome this issue is appreciated.
Eventually, I solved the issue as recommended by #coralvanda by setting the initial value as None, then doing the checking and updating inside a callback function.
dcc.DatePickerSingle(id='previ_date',
min_date_allowed=datetime.date(2022, 5, 10),
max_date_allowed=None,
initial_visible_month=None,
date=datetime.date.today())
#app.callback([Output("previ_date", "max_date_allowed"), Output("previ_date", "initial_visible_month")],
[Input("previ_date", "max_date_allowed"), Input("previ_date", "initial_visible_month")])
def update_date(max_date, current_month):
if max_date==None:
max_date=datetime.date.today()
if current_month==None:
current_month=datetime.date.today()
return max_date, current_month

Python - GCP Cloud Function issue with getting yesterdays date

I have a requirement of getting yesterdays date in my GCP Cloud Function which is written Python 3.9
This is the snippet I am using
from datetime import datetime, timedelta
cur_dt = datetime.today()
str_dt = str((datetime.today() - timedelta(1)).strftime('%Y-%m-%d'))
print(cur_dt)
print(str_dt)
This is working fine in Jupyter notebook. But if I place this same code in my cloud function, it fails to compile.
This is the error message I am getting: - Function failed on loading user code. This is likely due to a bug in the user code.
Would be of great help if anyone can help me fixing this error. This is strange and I dont understand why CLoud function isnt accepting something that is working fine in Jupyter notebook
Many Thanks in Advance.
As mentioned you need to follow the Cloud Functions schema which requires an entrypoint function that takes in the request parameter. Here is a codelab that walks through setting up a Cloud Function.
Your code should be updated to the following:
# imports
from datetime import datetime, timedelta
# entrypoint function with request param
def get_time(request):
cur_dt = datetime.today()
str_dt = str((datetime.today() - timedelta(1)).strftime('%Y-%m-%d'))
# can still print here if you want
return str_dt
If you are going through the UI make sure to update the entrypoint field to be get_time or whatever you name your entrypoint function.

Python - Get current UTC time. Ignore computer clock always

Does anyone have any tips to get the current UTC time, from online somewhere, and write some decent python code assuming my computer clock is always wrong?
current_datetime = datetime.datetime.utcnow() #---> assume always wrong
current_datetime = datetime.datetime.now() #---> assume always wrong
Using '.utcnow()' or '.now()' both depend upon the accuracy of my computer clock.
I want to write the code assuming that if it runs from a computer with a bad clock, it still gets the correct time.
BACKGROUND:
I am trying to retool my code to entirely live in UTC time.
My use case is to do some time series analysis.
I keep finding myself accidentally being off 5 hours from EST, or off 1 hour from daylight savings when doing calculations.
The tools within the datetime.datetime objects are great, however it would be nice be able to flag some setting when importing the datetime library and prevent reading my computer clock entirely, to avoid any accidental clock badness issue.
EXAMPLE OF CODE I AM LOOKING FOR:
import datetime
import requests
#force datetime libaries to never read my computer clock:
datetime.some_settings_function( readcomputerclock = False/'Never' )
#get the current time with some API:
current_utc_date_and_time_from_online = requests.get(...) #some api get request
current_utc_datetime = transform( current_utc_date_and_time_from_oneline )
#Transform back and forth to UTC Epoch time:
current_utc_epoch = current_utc_datetime.timestamp()
current_utc_datetime_again = datetime.datetime.fromtimestamp(current_utc_epoch)
#current_utc_datetime == current_utc_datetime_again
#Trigger exception with new settings, when i accidentally write code
# that would ask datetime library to attempt to read computer clock:
fail_code_line = datetime.datetime.now()
# >>> trigger some exception here
TLDR; I am looking for a reliable UTC api for python, and a way to prevent datetime from ever reading my computer clock again.
UPDATE: After accepting the provided answer it has become clear to me for my purposes, trusting my computer clock for a few seconds after updating my computer clock from a trusted source, then asking my computer clock for UTC time within those few seconds is good enough. It is a feasible coding practice to write a "get UTC time now" code using all the information within the accepted answer, that is accurate to within a second or two. (No I have not done the statistical confidence interval posterior on the accuracy) It is then further feasible to write all the rest of my code such that all logic will assume UTC time.
Getting correct, timezone aware datetimes and unix timestamps
Turns out this question was rather about how to convert to / from unix timestamps and datetimes.
The correct solution in python 3 should be:
from datetime import datetime, timezone
# get the current utc time
t = datetime.now(timezone.utc)
# convert to unix, this will keep the utc timezone
unix = t.timestamp()
# convert back to datetime, specifying that the timestamp is in UTC
t2 = datetime.fromtimestamp(unix, tz=timezone.utc)
Other timezones
Since python 3.9, the stdlib has the zoneinfo library, you can use this to convert between timezones.
For python < 3.9, you have to use a thirdparty library like dateutil.
from datetime import datetime
from zoneinfo import ZoneInfo
now_berlin = datetime.now(ZoneInfo('Europe/Berlin'))
now_ny = now_berlin.astimezone(ZoneInfo('America/New_York'))
print('Time in Berlin:', now_berlin)
print('Time in New York', now_ny)
Actually using ntp instead of the computer clock
You can use ntplib:
from ntplib import NTPClient
from datetime import datetime, timezone
client = NTPClient()
response = client.request('europe.pool.ntp.org', version=3)
time = datetime.fromtimestamp(resp.tx_time, tz=timezone.utc)
Edit: I however don't see a real reason, why just from traveling this should go wrong:
from datetime import datetime, timezone
dt = datetime.now(timezone.utc)
for more information see: https://blog.ganssle.io/articles/2019/11/utcnow.html

Django-Background-Tasks: Initialize Task at midnight and repeat every midnight

Good day SO,
I am currently using Django, and the Django-Background-Tasks package. I have a periodic task that I need to run at midnight, and it is to be repeated every midnight.
I am a beginner at using the package, and am confused by the following:
How do I set the repeat parameter during initialization?
Here is my code:
from background_task import background
from datetime import datetime, date
today_date = datetime.datetime.today()
today_midnight = today_date.replace(hour=23, minute=59, second=59)
#background(schedule=today_midnight)
def send_reminders():...
send_reminders(repeat=Task.DAILY)
I wanted to set the parameter 'repeat' to task.DAILY, as stated in the documentation. However, I have encountered the following:
NameError: name 'Task' is not defined
I know I have to import something to define Task, but I couldn't find it. Can anyone help me?
This is defined in the background_task.models module [GitHub]. So you should import this with:
from background_task.models import Task
DAILY itself just specifies the number of seconds, so 24×60×60=86'400:
class Task(models.Model):
# ...
HOURLY = 3600
DAILY = 24 * HOURLY

How to create a unified unix-timestamp both on iOS and Python?

I am developing an iOS application that needs to sync with a Python based REST service on GAE.
In the python backend I create my timestamps like this:
def create_timestamp(date):
midnight = datetime.time(0)
date_midnight_time = datetime.datetime.combine(date.date(), midnight)
return calendar.timegm(date_midnight_time.utctimetuple())
I pass in the function above datetime.datetime.today(). This would return for 27 Oct 2013 00:00:00 the value 1382832000.
On iOS there is a buildin function for that:
nextDate is set to today's date a bit complicated due an algorithm:
NSDate *date = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:(NSEraCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit) fromDate:date];
[components setDay:27];
NSDate *nextDate = [calendar dateFromComponents:components];
[nextDate timeIntervalSince1970] which returns for 2013-10-27 00:00:00 BST the value 1382828400.000000
There is some discrepancy though.
Maybe its because that Python side is UTC and iOS shows the time in BST by default and I need to address that. As of last night the British Summer time is no more, but iOS still reports BST. Thats confusing though as a NSDate object is always in UTC from my understanding....
Once its working, is it safe to cast the iOS double
value to int, in order to get a round integer number similar to the Python side?
I know this is old, but I thought I'd respond, since this particular issue is something I've been looking for an answer for for a while:
The IOS timestamp you give refers to the correct midnight for GMT of that date.
The python timestamp you give refers to one hour earlier (11:00 pm on the prior day).
This took me forever to find, and it's a pretty smart way of doing it (particularly when you consider the many more circuitous options I've seen):
I tried this, and it works nicely when trying to get the timestamp for a datetime in your local zone (but..):
from datetime import datetime
def dt_to_timestamp(dt_object):
"""Not really a good, universal solution"""
return eval(dt_object.strftime('%s.%f'))
dt_to_timestamp(datetime.now()) - time.time()
# -0.0002155303955078125
..but it fails pretty badly once it comes to looking at objects outside of your local zone:
from tzlocal import get_localzone
from pytz import utc
utc_now = datetime.now(tz=localzone).astimezone(utc)
dt_to_timestamp(utc_now) - time.time()
# 21599.98956131935, more commonly known as 21600 -- my offset from UTC
This is what I finally ended up with:
from datetime import datetime
from pytz import utc
def dt_to_timestamp(dt_object):
"""Provides timestamp for any zone-aware datetime object.
Works with Python 2.7 and Python 3.3, possibly others.
Raises TypeError when naive datetime objects are given.
"""
epoch = datetime(1970, 1, 1, tzinfo=utc)
delta = dt_object - epoch
return delta.total_seconds()
# example usage:
from tzlocal import get_localzone
ts = 1382832000
utc_dt = utc.localize(datetime.utcfromtimestamp(ts))
local_dt = utc_dt.astimezone(get_localzone())
ts == dt_to_timestamp(utc_dt) == dt_to_timestamp(local_dt)
# True
It handles aware datetime objects accurately, whatever their timezone. If the caller doesn't know the timezone in order to turn it into an aware timezone, then there are other problems. :-) I'm of the opinion that one should always use an aware datetime objects if possible, and when not using aware datetime objects, use UTC datetimes.
I found the info for this answer (amongst a lot of other detail) here.

Categories