I'm trying to display my full time zone along with my current local time.
print "Your current time is {0} {1} ".format(datetime.datetime.now().time(), time.tzname[0])
And the result would look something like:
Your current time is 08:35:45.328000 Pacific Standard Time
The problem is I have to import the Time library (sorry if I call it wrong, I'm coming from C#) along with the Datetime library.
import datetime
import time
I've looked into the naive and aware states of time, but still can't seem to get the desired result.
Is there a way to get the full timezone name (i.e.: Pacific Standard Time) from Datetime without having to import Time?
The example for writing your own local timezone tzinfo class uses (scroll down one page from here) pulls the tzname from time.tzname, so Python doesn't have a better built-in solution to suggest.
You could copy that example LocalTimezone implementation, which would allow the use of the %Z format code for strftime on an aware datetime instance using the LocalTimezone, but that's the best you can do with the built-ins. On a naive datetime the tzname is the empty string, so you need an aware datetime for this to work.
From Facebook Graph API I retrieve events which have the start_time set as string with the following format: "2012-10-12T23:30:00+0200". When location is specified it returns also the event object contains also the timezone (e.g.: "Europe/Rome").
I simply would like to check which events are upcoming (newer than "now").
I wonder if there is a way to do so without using pytz, which is not installed by default in Django. For deployment, the more portable the solution is the better.
You can use the built-in datetime module after a quick parse of the returned string (using "-", "T", and "+" as tokens).
Here is a quick reference to the documentation : http://docs.python.org/library/datetime.html
Note : this module handles timezone (search for tzone in the page).
I was programming a program in Python, where I need to output date as per user's locale:
Get a list of timezones in a country specified as per user input (did that using pytz)
Get the locale of the user (which I am unable to figure out how to do)
Is there a way to get locale from county/timezone or some other method needs to be followed?
Or do I need to get the locale input from user itself?
EDIT
The program is to be a web-app. The user can provide me his country. But does he have to explicitly provide me the locale also or can I get it from his timezone/country?
"Locale" is a country + language pair.
You have country + timezone. But no info about the language.
I don't think it's possible to convert country + timezone into a single 'correct' locale... in countries with multiple languages there is not a 1:1 relation between language and timezone.
The closest I can see is to use Babel:
from babel import Locale
Locale.parse('und_BR') # 'und' here means unknown language, BR is country
>>> Locale('pt', territory='BR')
This gives you a single 'most likely' (or default) locale for the country. To handle the languages properly you need to ask the user their preferred language.
In a Python project I'm working on, I'd like to be able to get a "human-readable" timezone name of the form America/New_York, corresponding to the system local timezone, to display to the user. Every piece of code I've seen that accesses timezone information only returns either a numeric offset (-0400) or a letter code (EDT) or sometimes both. Is there some Python library that can access this information, or if not that, convert the offset/letter code into a human-readable name?
If there's more than one human-readable name corresponding to a particular timezone, either a list of the possible results or any one of them is fine, and if there is no human-readable name corresponding to the current time zone, I'll take either an exception or None or [] or whatever.
A clarification: I don't remember exactly what I had in mind when I originally wrote this question, but I think what I really wanted was a way to turn a timezone into a human-readable name. I don't think this question was meant to focus on how to get the system local timezone specifically, but for the specific use case I had in mind, it just happened that the local timezone was the one I wanted the name for. I'm not editing the bit about the local timezone out of the question because there are answers focusing on both aspects.
The following generates a defaultdict mapping timezone offsets (e.g. '-0400') and abbreviations (e.g. 'EDT') to common geographic timezone names (e.g. 'America/New_York').
import os
import dateutil.tz as dtz
import pytz
import datetime as dt
import collections
result = collections.defaultdict(list)
for name in pytz.common_timezones:
timezone = dtz.gettz(name)
now = dt.datetime.now(timezone)
offset = now.strftime('%z')
abbrev = now.strftime('%Z')
result[offset].append(name)
result[abbrev].append(name)
for k, v in result.items():
print(k, v)
Note that timezone abbreviations can have vastly different meanings. For example, 'EST' could stand for Eastern Summer Time (UTC+10) in Australia, or Eastern Standard Time (UTC-5) in North America.
Also, the offsets and abbreviations may change for regions that use daylight standard time. So saving the static dict may not provide the correct timezone name 365 days a year.
I'd like to be able to get a "human-readable" timezone name of the form America/New_York, corresponding to the system local timezone, to display to the user.
There is tzlocal module that returns a pytz tzinfo object (before tzlocal 3.0 version) that corresponds to the system local timezone:
#!/usr/bin/env python
import tzlocal # $ pip install tzlocal
# display "human-readable" name (tzid)
print(tzlocal.get_localzone_name())
# Example Results:
# -> Europe/Moscow
# -> America/Chicago
To answer the question in the title (for people from google), you could use %Z%z to print the local time zone info:
#!/usr/bin/env python
import time
print(time.strftime('%Z%z'))
# Example Results:
# -> MSK+0300
# -> CDT-0500
It prints the current timezone abbreviation and the utc offset corresponding to your local timezone.
http://pytz.sourceforge.net/ may be of help. If nothing else, you may be able to grab a list of all of the timezones and then iterate through until you find one that matches your offset.
This may not have been around when this question was originally written, but here is a snippet to get the time zone official designation:
>>> eastern = timezone('US/Eastern')
>>> eastern.zone
'US/Eastern'
Further, this can be used with a non-naive datetime object (aka a datetime where the actual timezone has been set using pytz.<timezone>.localize(<datetime_object>) or datetime_object.astimezone(pytz.<timezone>) as follows:
>>> import datetime, pytz
>>> todaynow = datetime.datetime.now(tz=pytz.timezone('US/Hawaii'))
>>> todaynow.tzinfo # turned into a string, it can be split/parsed
<DstTzInfo 'US/Hawaii' HST-1 day, 14:00:00 STD>
>>> todaynow.strftime("%Z")
'HST'
>>> todaynow.tzinfo.zone
'US/Hawaii'
This is, of course, for the edification of those search engine users who landed here. ... See more at the pytz module site.
If you want only literally what you asked for, "the timezone name of the form America/New_York, corresponding to the system local timezone", and if you only care about Linux (and similar), then this should do the job:
import os
import os.path
import sys
def main(argv):
tzname = os.environ.get('TZ')
if tzname:
print tzname
elif os.path.exists('/etc/timezone'):
print file('/etc/timezone').read()
else:
sys.exit(1)
if __name__ == '__main__':
main(sys.argv)
Of course it would be nicer to have a library that encapsulates this in a cleaner way, and that perhaps handles the other cases you mention in comments like already having a tzinfo object. I think you can do that with pytz mentioned by Amber but it's not obvious to me just how...
Check out python-dateutil
py> from dateutil.tz import *
py> ny = gettz('America/New York')
py> ny._filename
'/usr/share/zoneinfo/America/New_York'
py> ny._filename.split('/', 4)[-1]
'America/New_York'
# use tzlocal library
from tzlocal import get_localzone
current_timezone = get_localzone()
zone = current_timezone.zone
print(zone)
Working with the latest version of tzlocal which is 4.1 as of today, tzlocal.get_localzone().key produces the following error: AttributeError: '_PytzShimTimezone' object has no attribute 'key'. But tzlocal.get_localzone().zone works lovely.
In my Django application I get times from a webservice, provided as a string, that I use in my templates:
{{date.string}}
This provides me with a date such as:
2009-06-11 17:02:09+0000
These are obviously a bit ugly, and I'd like to present them in a nice format to my users. Django has a great built in date formatter, which would do exactly what I wanted:
{{ value|date:"D d M Y" }}
However this expects the value to be provided as a date object, and not a string. So I can't format it using this. After searching here on StackOverflow pythons strptime seems to do what I want, but being fairly new to Python I was wondering if anyone could come up with an easier way of getting date formatting using strings, without having to resort to writing a whole new custom strptime template tag?
You're probably better off parsing the string received from the webservice in your view code, and then passing the datetime.date (or string) to the template for display. The spirit of Django templates is that very little coding work should be done there; they are for presentation only, and that's why they go out of their way to prevent you from writing Python code embedded in HTML.
Something like:
from datetime import datetime
from django.shortcuts import render_to_response
def my_view(request):
ws_date_as_string = ... get the webservice date
the_date = datetime.strptime(ws_date, "%Y-%m-%d %H:%M:%S+0000")
return render_to_response('my_template.html', {'date':the_date})
As Matthew points out, this drops the timezone. If you wish to preserve the offset from GMT, try using the excellent third-party dateutils library, which seamlessly handles parsing dates in multiple formats, with timezones, without having to provide a time format template like strptime.
This doesn't deal with the Django tag, but the strptime code is:
d = strptime("2009-06-11 17:02:09+0000", "%Y-%m-%d %H:%M:%S+0000")
Note that you're dropping the time zone info.