本文整理汇总了Python中time.tzset函数的典型用法代码示例。如果您正苦于以下问题:Python tzset函数的具体用法?Python tzset怎么用?Python tzset使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了tzset函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: get_messages
def get_messages():
os.environ['TZ'] = 'Asia/Shanghai'
time.tzset()
db = MySQLdb.connect("localhost","root","dhdj513758","iems5722")
chatroom_id = request.args.get("chatroom_id",0,type = int)
page = request.args.get("page",0,type = int)
query = "SELECT * FROM messages WHERE chatroom_id = %s"
params = (chatroom_id,)
cursor = db.cursor()
cursor.execute(query,params)
messages =cursor.fetchall()
string_t = []
if messages is None:
db.close()
return jsonify(message="<error message>",status="ERROR")
else:
for row in messages:
roww = {}
roww["message"]=row[4]
roww["user_id"]=row[2]
roww["name"]=row[3]
roww["timestamp"]=str(row[5])
string_t.append(roww)
messages_num = cursor.execute(query,params)
total_pages = messages_num / 5 + 1
string_u = string_t[::-1]
string = string_u[page * 5 - 5:page * 5]
data = {
"current_page":page,
"messages":string,
"total_pages":total_pages,
}
db.close()
return jsonify(data=data,status="OK")
开发者ID:huangdanlei,项目名称:python,代码行数:34,代码来源:project.py
示例2: get_month
def get_month():
timestamp = int(time.time())
FORY = '%m'
os.environ["TZ"] = config.default_timezone
time.tzset()
format_str = time.strftime(FORY, time.localtime(timestamp))
return format_str
开发者ID:wbbim,项目名称:collipa,代码行数:7,代码来源:helpers.py
示例3: apply_django_settings
def apply_django_settings(siteconfig, settings_map=None):
"""
Applies all settings from the site configuration to the Django settings
object.
"""
if settings_map is None:
settings_map = get_django_settings_map()
for key, setting_data in settings_map.iteritems():
if key in siteconfig.settings:
value = siteconfig.get(key)
if isinstance(setting_data, dict):
setting_key = setting_data['key']
if ('deserialize_func' in setting_data and
callable(setting_data['deserialize_func'])):
value = setting_data['deserialize_func'](value)
else:
setting_key = setting_data
setattr(settings, setting_key, value)
if hasattr(time, 'tzset'):
os.environ['TZ'] = settings.TIME_ZONE
time.tzset()
开发者ID:AndreasEisele,项目名称:wikitrans-pootle,代码行数:26,代码来源:django_settings.py
示例4: read
def read(self, configs, reload=False):
# sys.stderr.write("url.read\n")
self.cache = None
self.metadata = {}
config = None
try:
config = ConfigParser.ConfigParser()
fp = urllib2.urlopen(self.resource)
headers = dict(fp.info())
config.readfp(fp)
fp.close()
self.layers = {}
self._loadSections(config, configs, reload, cache=self.cache)
##### set last_mtime #####
os.environ["TZ"] = "UTC"
time.tzset()
# FIXME fixed format is probably wrong
mytime = time.strptime(headers["last-modified"], "%a, %d %b %Y %H:%M:%S %Z")
self.last_mtime = time.mktime(mytime)
except Exception, E:
self.metadata["exception"] = E
self.metadata["traceback"] = "".join(traceback.format_tb(sys.exc_traceback))
开发者ID:sq9mev,项目名称:TileCache,代码行数:26,代码来源:Url.py
示例5: setUpMyTime
def setUpMyTime():
# Set the time to a fixed, known value
# Sun Aug 14 12:00:00 CEST 2005
# yoh: we need to adjust TZ to match the one used by Cyril so all the timestamps match
os.environ['TZ'] = 'Europe/Zurich'
time.tzset()
MyTime.setTime(1124013600)
开发者ID:AlexanderSk,项目名称:fail2ban,代码行数:7,代码来源:utils.py
示例6: setup
def setup(bot):
time.tzset()
ctime = time.time()
bot.memory['kd_queue']=[]
try:
bot.memory['kd_evnctr']=int(bot.config.kdown.ev_ctr)
except:
bot.memory['kd_evnctr']=0
print(bot.config.kdown.events)
events=unpack_events(bot, bot.config.kdown.events)
bot.memory['kd_events']=events
print(bot.memory['kd_events'])
print()
print(bot.memory['kd_queue'])
try:
subscrl=bot.config.kdown.get_list('subscribers')
bot.memory['kd_subscribers']=set()
for sub in subscrl:
bot.memory['kd_subscribers'].add(sub)
print(subscrl,bot.memory['kd_subscribers'])
except Exception as e:
bot.memory['kd_subscribers']=set()
bot.memory.setdefault('ctmutex', threading.BoundedSemaphore(1)) #CheckTime Mutex
lstr = lambda o: str(o).lower()
admins=set(map(lstr, bot.config.core.get_list('admins')))
admins.update(set(map(lstr, bot.config.kdown.get_list('admins'))))
admins.add(bot.config.core.owner)
bot.memory['kd_admins'] = admins
开发者ID:ChaoticWeg,项目名称:kountdown,代码行数:33,代码来源:kountdown.py
示例7: testApprovedTZFromEnvironmentWithFloating
def testApprovedTZFromEnvironmentWithFloating(self):
def _restoreTZEnv(result, oldTZ):
if oldTZ is None:
del os.environ['TZ']
else:
os.environ['TZ'] = oldTZ
time.tzset()
eventcalendar.tz.LOCAL = tz.LocalTimezone()
return result
new_end_naive = self.half_an_hour_ago.replace(tzinfo=None)
oldTZ = os.environ.get('TZ', None)
os.environ['TZ'] = 'US/Pacific'
time.tzset()
eventcalendar.tz.LOCAL = tz.LocalTimezone()
data = self.ical_from_specs('', self.half_an_hour_ago,
'', new_end_naive)
self.bouncer = self.bouncer_from_ical(data)
keycard = keycards.KeycardGeneric()
d = defer.maybeDeferred(self.bouncer.authenticate, keycard)
d.addCallback(self._approved_callback)
d.addBoth(_restoreTZEnv, oldTZ)
return d
开发者ID:ApsOps,项目名称:flumotion-orig,代码行数:27,代码来源:test_icalbouncer.py
示例8: __init__
def __init__(self):
with open('config.json', 'r') as f:
self.config = json.load(f)
self.conn = Redis(self.config['redis']['host'])
os.environ['TZ'] = 'EST'
time.tzset()
开发者ID:treylitefm,项目名称:medio,代码行数:7,代码来源:model.py
示例9: get_year
def get_year():
timestamp = int(time.time())
FORY = '%Y'
os.environ["TZ"] = config.default_timezone
time.tzset()
str = time.strftime(FORY, time.localtime(timestamp))
return str
开发者ID:Quasimo,项目名称:collipa,代码行数:7,代码来源:helpers.py
示例10: reload_django_settings
def reload_django_settings():
mod = util.import_module(os.environ['DJANGO_SETTINGS_MODULE'])
# reload module
reload(mod)
# reload settings.
# USe code from django.settings.Settings module.
# Settings that should be converted into tuples if they're mistakenly entered
# as strings.
tuple_settings = ("INSTALLED_APPS", "TEMPLATE_DIRS")
for setting in dir(mod):
if setting == setting.upper():
setting_value = getattr(mod, setting)
if setting in tuple_settings and type(setting_value) == str:
setting_value = (setting_value,) # In case the user forgot the comma.
setattr(settings, setting, setting_value)
# Expand entries in INSTALLED_APPS like "django.contrib.*" to a list
# of all those apps.
new_installed_apps = []
for app in settings.INSTALLED_APPS:
if app.endswith('.*'):
app_mod = util.import_module(app[:-2])
appdir = os.path.dirname(app_mod.__file__)
app_subdirs = os.listdir(appdir)
name_pattern = re.compile(r'[a-zA-Z]\w*')
for d in sorted(app_subdirs):
if (name_pattern.match(d) and
os.path.isdir(os.path.join(appdir, d))):
new_installed_apps.append('%s.%s' % (app[:-2], d))
else:
new_installed_apps.append(app)
setattr(settings, "INSTALLED_APPS", new_installed_apps)
if hasattr(time, 'tzset') and settings.TIME_ZONE:
# When we can, attempt to validate the timezone. If we can't find
# this file, no check happens and it's harmless.
zoneinfo_root = '/usr/share/zoneinfo'
if (os.path.exists(zoneinfo_root) and not
os.path.exists(os.path.join(zoneinfo_root,
*(settings.TIME_ZONE.split('/'))))):
raise ValueError("Incorrect timezone setting: %s" %
settings.TIME_ZONE)
# Move the time zone info into os.environ. See ticket #2315 for why
# we don't do this unconditionally (breaks Windows).
os.environ['TZ'] = settings.TIME_ZONE
time.tzset()
# Settings are configured, so we can set up the logger if required
if getattr(settings, 'LOGGING_CONFIG', False):
# First find the logging configuration function ...
logging_config_path, logging_config_func_name = settings.LOGGING_CONFIG.rsplit('.', 1)
logging_config_module = util.import_module(logging_config_path)
logging_config_func = getattr(logging_config_module, logging_config_func_name)
# ... then invoke it with the logging settings
logging_config_func(settings.LOGGING)
开发者ID:RobKmi,项目名称:guru,代码行数:60,代码来源:django_wsgi.py
示例11: setUp
def setUp(self):
# Ensure we're in UTC.
os.environ['TZ'] = 'UTC'
time.tzset()
# Start with a fresh api proxy.
apiproxy_stub_map.apiproxy = apiproxy_stub_map.APIProxyStubMap()
# Use a fresh stub datastore.
self.__datastore_stub = datastore_file_stub.DatastoreFileStub(
APP_ID, '/dev/null', '/dev/null')
apiproxy_stub_map.apiproxy.RegisterStub(
'datastore_v3', self.__datastore_stub)
os.environ['APPLICATION_ID'] = APP_ID
# Use a fresh stub UserService.
apiproxy_stub_map.apiproxy.RegisterStub(
'user', user_service_stub.UserServiceStub())
os.environ['AUTH_DOMAIN'] = AUTH_DOMAIN
os.environ['USER_EMAIL'] = LOGGED_IN_USER
# Use a fresh urlfetch stub.
apiproxy_stub_map.apiproxy.RegisterStub(
'urlfetch', urlfetch_stub.URLFetchServiceStub())
# Use a fresh mail stub.
apiproxy_stub_map.apiproxy.RegisterStub(
'mail', mail_stub.MailServiceStub())
开发者ID:GunioRobot,项目名称:freesideatlanta-members,代码行数:28,代码来源:test_util.py
示例12: __init__
def __init__(self):
Cmd.__init__(self)
os.environ["TZ"] = "UTC"
time.tzset()
# Try parsing just the arguments that make sense if we're
# going to be running an interactive command loop. If that
# parses everything, we're interactive, otherwise, it's either
# a non-interactive command or a parse error, so we let the full
# parser sort that out for us.
args, argv = self.top_argparser.parse_known_args()
self.interactive = not argv
if not self.interactive:
args = self.full_argparser.parse_args()
self.cfg_file = args.config
self.handle = args.identity
if args.profile:
import cProfile
prof = cProfile.Profile()
try:
prof.runcall(self.main, args)
finally:
prof.dump_stats(args.profile)
print "Dumped profile data to %s" % args.profile
else:
self.main(args)
开发者ID:pavel-odintsov,项目名称:RPKI-toolkit,代码行数:30,代码来源:rpkic.py
示例13: updateTime
def updateTime(self, event = None):
"""When this is called, update all the text boxes with the correct time"""
boxWidth = 80 #used to force the window to be the correct width
for [tz, title, format, wxtextbox] in self.config:
os.environ['TZ'] = tz #set the TZ to that given in the config
time.tzset() #set the time zone in the time module
dateStr = time.strftime(format) + " " + title
boxWidth = max(boxWidth, len(dateStr)*self.pixlesPerCharX)
wxtextbox.SetValue(dateStr)
if self.paintFormat == self.__PAINT_DIURNAL__ and \
int(time.strftime("%H")) >= 7 and int(time.strftime("%H")) <= 19: #rudimentary check for daylight
wxtextbox.SetBackgroundColour(wx.Colour(self.bgA[0], self.bgA[1], self.bgA[2]))
if self.paintFormat == self.__PAINT_DIURNAL__ and \
int(time.strftime("%H")) < 7 or int(time.strftime("%H")) > 19: #checking for daylight
wxtextbox.SetBackgroundColour(wx.Colour(self.bgB[0], self.bgB[1], self.bgB[2]))
for i in range(len(self.config)): #set smallest size and colorize
self.config[i][3].SetMinSize([boxWidth, 27]) #set smallest size
if (i % 2) == 0 and self.paintFormat == self.__PAINT_ALTERNATING__:
self.config[i][3].SetBackgroundColour(wx.Colour(self.bgA[0], self.bgA[1], self.bgA[2]))
if (i % 2) == 1 and self.paintFormat == self.__PAINT_ALTERNATING__:
self.config[i][3].SetBackgroundColour(wx.Colour(self.bgB[0], self.bgB[1], self.bgB[2]))
self.SetMinSize([boxWidth, -1])
self.SetMaxSize([boxWidth, 27*len(self.config)])
try:
event.Skip
except:
pass
开发者ID:npotts,项目名称:laughing-dangerzone,代码行数:27,代码来源:pyTime.py
示例14: activateTimezone
def activateTimezone(self, tz, tzarea):
if path.exists("/usr/lib/enigma2/python/Plugins/Extensions/AutoTimer/plugin.pyo") and config.plugins.autotimer.autopoll.value:
print "[Timezones] trying to stop main AutoTimer poller"
self.autopoller.stop()
self.ATupdate = True
if tzarea == Timezones.gen_label:
fulltz = tz
else:
fulltz = "%s/%s" % (tzarea, tz)
tzneed = "%s/%s" % (Timezones.tzbase, fulltz)
if not path.isfile(tzneed):
print "[Timezones] Attempt to set timezone", fulltz, "ignored. UTC used"
fulltz = "UTC"
tzneed = "%s/%s" % (Timezones.tzbase, fulltz)
print "[Timezones] setting timezone to", fulltz
environ['TZ'] = fulltz
try:
unlink("/etc/localtime")
except OSError:
pass
try:
symlink(tzneed, "/etc/localtime")
except OSError:
pass
try:
time.tzset()
except:
from enigma import e_tzset
e_tzset()
if path.exists("/usr/lib/enigma2/python/Plugins/Extensions/AutoTimer/plugin.pyo") and config.plugins.autotimer.autopoll.value:
self.startATupdate()
开发者ID:rimasx,项目名称:enigma2,代码行数:34,代码来源:Timezones.py
示例15: main
def main():
logging.warning(
'devappserver2.py is currently experimental but will eventually replace '
'dev_appserver.py in the App Engine Python SDK. For more information and '
'to report bugs, please see: '
'http://code.google.com/p/appengine-devappserver2-experiment/')
_install_signal_handler()
# The timezone must be set in the devappserver2 process rather than just in
# the runtime so printed log timestamps are consistent and the taskqueue stub
# expects the timezone to be UTC. The runtime inherits the environment.
os.environ['TZ'] = 'UTC'
if hasattr(time, 'tzset'):
# time.tzet() should be called on Unix, but doesn't exist on Windows.
time.tzset()
options = parse_command_arguments(sys.argv[1:])
dev_server = DevelopmentServer()
try:
dev_server.start(options)
while True:
time.sleep(1)
except KeyboardInterrupt:
pass
finally:
dev_server.stop()
开发者ID:Weirdln,项目名称:goagent,代码行数:25,代码来源:devappserver2.py
示例16: getTodayDate
def getTodayDate(self):
import os, time
os.environ['TZ'] = "Europe/London"
time.tzset()
localtime = time.localtime()
timeString = time.strftime('%Y%m%d')
return(timeString)
开发者ID:HeinzSchmidt,项目名称:shopping,代码行数:7,代码来源:__init__.py
示例17: update_connections_time_zone
def update_connections_time_zone(**kwargs):
if kwargs['setting'] == 'TIME_ZONE':
# Reset process time zone
if hasattr(time, 'tzset'):
if kwargs['value']:
os.environ['TZ'] = kwargs['value']
else:
os.environ.pop('TZ', None)
time.tzset()
# Reset local time zone cache
timezone.get_default_timezone.cache_clear()
# Reset the database connections' time zone
if kwargs['setting'] in {'TIME_ZONE', 'USE_TZ'}:
for conn in connections.all():
try:
del conn.timezone
except AttributeError:
pass
try:
del conn.timezone_name
except AttributeError:
pass
conn.ensure_timezone()
开发者ID:aetos1918,项目名称:Django,代码行数:25,代码来源:signals.py
示例18: test_TimeRE_recreation_timezone
def test_TimeRE_recreation_timezone(self):
# The TimeRE instance should be recreated upon changing the timezone.
oldtzname = time.tzname
tm = _strptime._strptime_time(time.tzname[0], '%Z')
self.assertEqual(tm.tm_isdst, 0)
tm = _strptime._strptime_time(time.tzname[1], '%Z')
self.assertEqual(tm.tm_isdst, 1)
# Get id of current cache object.
first_time_re = _strptime._TimeRE_cache
# Change the timezone and force a recreation of the cache.
os.environ['TZ'] = 'EST+05EDT,M3.2.0,M11.1.0'
time.tzset()
tm = _strptime._strptime_time(time.tzname[0], '%Z')
self.assertEqual(tm.tm_isdst, 0)
tm = _strptime._strptime_time(time.tzname[1], '%Z')
self.assertEqual(tm.tm_isdst, 1)
# Get the new cache object's id.
second_time_re = _strptime._TimeRE_cache
# They should not be equal.
self.assertIsNot(first_time_re, second_time_re)
# Make sure old names no longer accepted.
with self.assertRaises(ValueError):
_strptime._strptime_time(oldtzname[0], '%Z')
with self.assertRaises(ValueError):
_strptime._strptime_time(oldtzname[1], '%Z')
开发者ID:Dongese,项目名称:cpython,代码行数:25,代码来源:test_strptime.py
示例19: __init__
def __init__(self, init_data, raw_feed=None, has_icon=None,
icon=None, feedhandler=None, feedtype='usual'):
GObject.GObject.__init__(self)
tzset()
self.url = init_data["url"]
self.name = init_data["feed_name"]
self.automatic_update = init_data["update_switch"]
self.notifications = init_data["notify_switch"]
self.update_interval = init_data["update_spin"]
self.delete_interval = init_data["delete_spin"]
self.new_entries = []
self.has_icon = has_icon
self.icon = icon
self.feedtype = feedtype
self.is_clicked = False
self.count_new_entries = 0
self.raw_feed = raw_feed
if raw_feed is None:
self._download_data()
self.update_id = None
self.add_updater(self.update_interval)
开发者ID:nanamii,项目名称:gylfeed,代码行数:25,代码来源:feed.py
示例20: update_connections_time_zone
def update_connections_time_zone(**kwargs):
if kwargs["setting"] == "TIME_ZONE":
# Reset process time zone
if hasattr(time, "tzset"):
if kwargs["value"]:
os.environ["TZ"] = kwargs["value"]
else:
os.environ.pop("TZ", None)
time.tzset()
# Reset local time zone cache
timezone.get_default_timezone.cache_clear()
# Reset the database connections' time zone
if kwargs["setting"] == "USE_TZ" and settings.TIME_ZONE != "UTC":
USE_TZ, TIME_ZONE = kwargs["value"], settings.TIME_ZONE
elif kwargs["setting"] == "TIME_ZONE" and not settings.USE_TZ:
USE_TZ, TIME_ZONE = settings.USE_TZ, kwargs["value"]
else:
# no need to change the database connnections' time zones
return
tz = "UTC" if USE_TZ else TIME_ZONE
for conn in connections.all():
conn.settings_dict["TIME_ZONE"] = tz
tz_sql = conn.ops.set_time_zone_sql()
if tz_sql:
conn.cursor().execute(tz_sql, [tz])
开发者ID:daiqingyang,项目名称:django,代码行数:27,代码来源:signals.py
注:本文中的time.tzset函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论