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
Related
I need to filter the lines where the date is today and not more than 2 hours ago according to local time (the code needs to be malleable as I travel to different timezones):
from tzlocal import get_localzone
import pandas as pd
import pytz
df['DATA_HORA'] = df.apply(lambda x: datetime.strptime(f'{x["DATA"]} {x["HORA"]}', '%d/%m/%Y %H:%M'), axis=1)
local_tz = get_localzone()
local_tz = pytz.timezone(local_tz.zone)
df_today = df[(df['DATA_HORA'].dt.tz_localize(local_tz) >= (datetime.now(local_tz) - timedelta(hours=2))) & (df['DATA_HORA'].dt.date == datetime.now(local_tz).date())]
I tried to understand how to do it, according to the specific documentation about it:
https://pytz-deprecation-shim.readthedocs.io/en/latest/migration.html#getting-a-time-zone-s-name
But I was not successful, how should I proceed to find my local timezone and not receive this warning anymore?
tzlocal.get_localzonealready returns a timezone object, which you can use directly:
import pandas as pd
from tzlocal import get_localzone
z = get_localzone()
print(repr(z))
# _PytzShimTimezone(zoneinfo.ZoneInfo(key='Europe/Berlin'), 'Europe/Berlin')
print(pd.Timestamp("now", tz=z))
# 2023-02-14 17:54:32.445179+01:00
You can also unwrap it and obtain the string representation in a way that doesn't trigger warnings:
print(repr(z.unwrap_shim()))
# zoneinfo.ZoneInfo(key='Europe/Berlin')
print(z.unwrap_shim().key)
# Europe/Berlin
...or also like
from tzlocal import get_localzone_name
print(get_localzone_name())
# Europe/Berlin
Note that if you use pandas, you neither need the datetime module nor pytz here.
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)
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.
I'm trying to list out tweets with their time-stamps. I have this...
#!/usr/bin/python
import twitter
api = twitter.Api()
statuses = api.GetUserTimeline('ttytter')
for s in statuses:
print s.created_at + " " + s.text
Which prints out...
Sat Oct 20 04:56:47 +0000 2012 #uriel1998 W/r/t DMs, they appear just fine in 2.0.4 and 2.1 beta here, near as I can tell.
Which is pretty much what I'm after, but for the time, which seems to be in the wrong timezone. https://twitter.com/ttytter/status/259518502069760000
Is there a way I can change this within the python-twitter library? I was looking at GetTimeZone() and SetTimeZone(), but I haven't been able to figure out how they work.
Also looking at how to shift a datetime object by 12 hours in python but not sure if I need to go there.
Thanks for any help!
python-twitter returns the status timestamps as a string and as the number of seconds since the epoch. The latter is the simplest to convert to a timezone-aware datetime instance (see this answer).
Unfortunately the user's time_zone attribute is not in the standard tz database format used by pytz, so it is necessary to use the utc_offset user attribute instead (we still use the time_zone attribute to name the tzinfo created with with the UTC offset). The python-dateutil package provides a convenience type tzoffset that allows the creation of tzinfo instances from UTC offsets, which we can then use to convert the datetime from UTC to the local time zone:
import pytz
import twitter
from datetime import datetime
from dateutil.tz import tzoffset
USERNAME = 'ttytter'
api = twitter.Api()
# get a 'tzinfo' instance with the UTC offset for the user's local time
user = api.GetUser(USERNAME)
localtime_tz = tzoffset(user.time_zone, user.utc_offset)
statuses = api.GetUserTimeline(USERNAME)
for s in statuses[:1]:
# get UTC timestamp from seconds since epoch
utc_dt = datetime.utcfromtimestamp(s.created_at_in_seconds).replace(tzinfo=pytz.utc)
print('utc: {}'.format(utc_dt))
# convert to local time in the user's timezone
localtime_dt = utc_dt.astimezone(localtime_tz)
print('localtime [{}]: {}'.format(localtime_dt.tzname(), localtime_dt))
which gives the output for the first status:
utc: 2012-10-20 04:56:47+00:00
localtime [Pacific Time (US & Canada)]: 2012-10-19 20:56:47-08:00
Combining suggestions from Pedro Romano and J.F. Sebastian, I have this...
import pytz
import twitter
from datetime import datetime
USERNAME = 'ttytter'
api = twitter.Api()
user = api.GetUser(USERNAME)
pst_tz = pytz.timezone('America/Los_Angeles')
statuses = api.GetUserTimeline(USERNAME)
for s in statuses[:1]:
# get UTC timestamp from seconds since epoch
utc_dt = datetime.utcfromtimestamp(s.created_at_in_seconds).replace(tzinfo=pytz.utc)
# convert to given timezone
pst_dt = pst_tz.normalize(utc_dt.astimezone(st_tz))
print(pst_dt.strftime('%Y-%m-%d %H:%M:%S ')) + s.text
Output: 2012-10-19 21:56:47 #uriel1998 W/r/t DMs, they appear just fine in 2.0.4 and 2.1 beta here, near as I can tell. which is the correct time zone and also accounts for DST.
Thank you!