I am trying to delete 3 years old data in my python django db. Here is code:
from datetime import datetime
from dateutil.relativedelta import relativedelta
def db_cleanup():
cleanup_start = datetime.utcnow().date()
three_years_ago = cleanup_start - relativedelta(years=3)
MyData.objects.filter(create_date__lt=three_years_ago).delete()
however I receive RuntimeWarning: DateTimeField received a naive datetime . How to do it properly?
Use timezone.now() to create an aware datetime then reset time to midnight but keep a datetime object (not date):
from django.utils import timezone
from dateutil.relativedelta import relativedelta
def db_cleanup():
cleanup_start = timezone.now().replace(hour=0, minute=0, second=0, microsecond=0)
three_years_ago = cleanup_start - relativedelta(years=3)
MyData.objects.filter(create_date__lt=three_years_ago).delete()
Related
I am looking to get the timezone of the physical, virtual, container node?
The following provides me with short timezone name -
import datetime
import dateutil.tz
tz_name = datetime.datetime.now(dateutil.tz.tzlocal()).tzname()
The above gives me MDT or EDT depending on the node's timezone.
How I can get the full timezone name e.g. America/New_York or America/Denver instead?
Edit:
OK I think the following would work for me -
from datetime import datetime
from tzlocal import get_localzone
_now = datetime.now(tz=get_localzone())
_now.tzinfo.key # prints America/New_York
I get the following publishedAt string '2021-08-24T11:00:19Z' from youtube's api for the video object. But I don;t understand how to convert it into a datetime object and find the hours between it and current.
I tried the below code but it didn't work
view.py
from django.utils import timezone
from datetime import datetime
today = timezone.now()
publishedAt = datetime.fromtimestamp('2021-08-24T11:00:19Z')
daysOld = (today - publishedAt).days
But I am getting the below error at this line publish_date = datetime.fromtimestamp('2021-08-24T11:00:19Z')
TypeError: an integer is required (got type str)
I don't understand how to convert the string to datetime object and get the difference.
The string you provide here is datetime formatted by the ISO 8601 standard [wiki]. You can parse this with the parser.isoparse(…) method [Python-doc] from the dateutil package:
>>> from dateutil.parser import isoparse
>>> isoparse('2021-08-24T11:00:19Z')
datetime.datetime(2021, 8, 24, 11, 0, 19, tzinfo=tzutc())
You thus can install the package with:
pip3 install python-dateutil
and then run this with:
from django.utils import timezone
from dateutil.parse import isoparse
today = timezone.now()
publish_date = isoparse('2021-08-24T11:00:19Z')
diff = today - publish_date
After a user logs in, I am setting a session variable to the time with utc.. but the timezone is getting stripped.
import datetime
from pytz import timezone
utc = timezone('utc')
session['login_time'] = datetime.datetime.now(utc)
When I print after the assignment the timezone is there 2021-06-11 23:56:00.161971+00:00. And a decorator function gets called. When I print session['login_time'] the timezone is removed. 2021-06-11 23:56:00
For me, I will use .strftime to help format the datetime and %Z is to show the timezone.
You can see the strftime document to help you format the time. I will use this code to replace your original one:
session['login_time'] = datetime.datetime.now(utc).strftime('"%Y-%m-%d %H:%M:%S%Z"')
login_time = datetime.datetime.strptime(session['login_time'],"%Y-%m-%d %H:%M:%S%Z" )
utct = utc.localize(login_time)
print(utct)
print(type(utct))
And here is the output:
2021-06-12 01:00:23+00:00
<class 'datetime.datetime'>
I had to re-add the timezone('utc') when i needed to use the time in another function.
def diff_min(t):
utc = timezone('utc')
t = utc.localize(t)
So I'm trying to prepare a message with Python that takes a Timestamp, but I'm having trouble converting a datetime to a protobuf Timestamp.
Here's what I've tried so far:
from google.protobuf.timestamp_pb2 import Timestamp
import datetime
now = datetime.datetime.now()
timestamp = Timestamp()
timestamp.FromDatetime(now)
However, I'm getting an error AttributeError: 'Timestamp' object attribute 'seconds' is read-only
How can I create a Timestamp from a datetime?
This code is working fine on my machine
from google.protobuf.timestamp_pb2 import Timestamp
import datetime
now = datetime.datetime.now()
timestamp = Timestamp()
timestamp.FromDatetime(now)
Output:
seconds: 1591859232
nanos: 803377000
i want to convert UTC time into user's browser time.
i have tried a loat but its display me system time only.
working with django application. can anybudy help me out.
import pytz
from tzlocal import get_localzone
def utc_to_local(utc_dt):#utc_dt that is UTC time
local_tz = get_localzone()
print local_tz #that is display system timezone inplace of USER's timezone
I have tried with below code.
import time
from datetime import datetime
from dateutil import tz
utc = datetime.strptime(str(utc_dt)[:19], '%Y-%m-%d %H:%M:%S')
return time.mktime(utc_dt.timetuple()) * 1000
convert utc time into second and then using javascript need to make it localtime. but conversion value not accurate and its display me wrong date.
Javascript code.
//1449206930000 #Seconds when above code run
//1449226703.79 #that is correct >> time.time() in python = 1449226703.79
#below code give perfact output
var date = new Date(parseInt(1449226703.79, 10) * 1000);
console.log(date);
#below code not working
var date = new Date(parseInt(1449206930000, 10) * 1000);
console.log(date);
Regards
You need to find the users timezone first, to convert time in there local timezone.
There are two ways to do it.
1) Pass simply UNIX-timestamp then use a Javascript to convert it in human readable time on the browser momentjs can help you with that.
function human_time(unixtime, tz) {
var t=moment.unix(unixtime);
return t.tz(tz).format('DD/MM/YY HH:mm:ss');
}
2) Use IP address or HTTP headers to detect the user location and then use pytz to convert your time in users system timezone instead of your own django/server timezone.
def get_user_timezone(request):
return request.visitor.location.timezone
def human_time(dt, tz="Asia/Kolkata"):
try:
tz = pytz.timezone(tz)
except:
tz = pytz.timezone("Asia/Kolkata")
dt = dt.astimezone(tz)
return dt.strftime(r'%d/%m/%Y %H:%M:%S %Z')
def view_get_local_time(request):
tz = get_user_timezone(request) #detect user timezone, base on IP
text = human_time(timezone.now(), tz) #convert server-time to detected timezone
return HttpResponse(text)
Note: First method is the most preferable method.
import time, calendar
import datetime
utc = datetime.datetime.strptime(str(timezone_rt)[:19], '%Y-%m-%d %H:%M:%S')
return time.mktime(time.localtime(calendar.timegm(utc.timetuple()))) #convert utc time into second that correct output like function time.time()
Thanks for help.