python 怎么linux 获取时区linux时区

Stay hungry, stay foolish.
2014年六月
91011121314
16171819202122
242526272829Python与Django的时区问题(转载)
的时区问题
datetime.today() / datetime.now()
这两个函数获得的是当前的时间,但得到的datetime对象中的tzinfo是空的,即使系统中设置了时区。
datetime.utcnow()
这个函数获得当前的utc时间,应该是根据当前系统时间和时区来计算的。
例如系统时间为14:00,时区为 Asia/Shanghai (北京时间),utcnow返回时间为
6:00。同样,得到的对象中的tzinfo 为空。
环境变量 TZ 对以上函数的影响:
当系统中设置了环境变量 TZ 的时候,或者在python中设置了 os.environ[‘TZ’]
的时候,上面的函数获取的时间便是TZ对应时区的时间。其实这里可以认为 TZ
影响的不是这些函数,而是影响的系统时间,这可以从date命令的返回结果看出。datetime.now() 与
date命令返回的结果总是一致的。
Django的时区问题
明白了上面几个python中的函数,django的时区问题看起来就简单了。
在django的setting中,有一个设置是 TIME_ZONE, 来设置程序中使用的时区。
从django的文档中得知,TIME_ZONE的作用就是改变 os.environ[‘TZ’]
&,但改变os.environ[‘TZ’]
&并不会改变系统环境变量 TZ , 因此,如果 TIME_ZONE
的设置于系统时区设置不一致,则在程序中 datetime.now() 获得的时间就与 date 命令的时间不一致了。
因此,TIME_ZONE 应该设置为程序希望使用的时区。对于一个本地的程序,TIME_ZONE
设置为与系统时区一样即可;而对于一个国际化的应用,TIME_ZONE
最好设置为UTC,在显示的时候再根据当前用户所在的时区做调整。
博文转载:
已投稿到:
以上网友发言只代表其个人观点,不代表新浪网的观点或立场。博客访问: 160567
博文数量: 52
注册时间:
ITPUB论坛APP
ITPUB论坛APP
APP发帖 享双倍积分
IT168企业级官微
微信号:IT168qiye
系统架构师大会
微信号:SACC2013
分类: Linux
我要解决的问题是,发现某个文件超过30分钟时间不被更新,则报警>>> t1=[,19,20,30] #日 19:30:30>>> last_time=datetime.datetime(t1[0],t1[1],t1[2].t1[3],t1[4],t1[5]) #上次更新时间>>> now_time = datetime.datetime.now() #当前时间>>> #以下是亮点>>> mkt_last = time.mktime(last_time.timetuple()) >>> mkt_now = time.mktime(now_time.timetuple())>>> delt_time = (mkt_now-mkt_last)/60&& #转成分钟>>> if (delt_time -30) > 0 :>>>&&&& print "超过30分钟没有更新啦!"
这是我在解决问题时,发现的其他一些有用的函数,呵呵,留着备用吧计算两个时间的差,如两个时间相差几天,几小时等1.计算两个日期相差天数的计算 >>> import datetime>>> d1 = datetime.datetime()>>> d2 = datetime.datetime()>>> (d1 - d2).days输出结果:472.计算两个时间相差的秒数>>> import datetime>>> starttime = datetime.datetime.now()>>> #long running>>> endtime = datetime.datetime.now()>>> print (endtime - starttime).seconds
3.计算当前时间向后10小时的时间>>> d1 = datetime.datetime.now()>>> d3 = d1 + datetime.timedelta(hours=10)>>> d3.ctime()
对时间的操作,其本上常用的类有:datetime和timedelta两个。它们之间可以相互加减。每个类都有一些方法和属性可以查看具体的值,如datetime可以查看:天数(day),小时数(hour),星期几(weekday())等;timedelta可以查看:天数(days),秒数(seconds)等。4.日期的操作必须使用time或datetime库 import time >>> s="" >>> time.strptime(s,"%Y-%m-%d) 这是将字符串格式的日期及时间转成日期对象 转义符对应意义如下 %a 本地简化星期名称 %A 本地完整星期名称 %b 本地简化的月份名称 %B 本地完整的月份名称 %c 本地相应的日期表示和时间表示 %d 月内中的一天(0-31) %H 24小时制小时数(0-23) %I 12小时制小时数(01-12) %j 年内的一天(001-366) %m 月份(01-12) %M 分钟数(00=59) %p 本地A.M.或P.M.的等价符 %S 秒(00-59) %U 一年中的星期数(00-53)星期天为星期的开始 %w 星期(0-6),星期天为星期的开始 %W 一年中的星期数(00-53)星期一为星期的开始 %x 本地相应的日期表示 %X 本地相应的时间表示 %y 两位数的年份表示(00-99) %Y 四位数的年份表示(000-9999) %Z 当前时区的名称 %% %号本身
阅读(29488) | 评论(0) | 转发(0) |
相关热门文章
给主人留下些什么吧!~~
原帖由Guest于 20:45:19发表
直接写shell完成岂不简单?
这个程序的其他功能的实现,是在python里面,需要使用python代码的
请登录后评论。申请博客有一段时间了,然而到现在还一篇没有写过。。。。。
主要因为没有想到需要写些什么,最近在学习Python语言,照着书上看了看最基础的东西,发现根本看不进去,而且光看的话今天看了觉得都理解懂了,过两天自己回顾这部分内容的时候发现就又忘了,于是自己就想到自己边学边写一些小程序,以便能更好的让自己记住语法。
一、开发环境以及测试环境
Python2.7.10、pycharm、VM虚拟机、CentOS6.3
二、代码实现
代码结构:
commands.py && os_info_in.py &&&os_info.py &|
                linux_status.py &|--&linux_status_main.py
commands.py:
实现在Python代码中运行Linux的命令,得到打印的结果集,并返回结果results
1 # coding=UTF-8
2 import os
3 class commands:
def __init__(self,comm):
def excute_command(self):
result = os.mend)
results = result.readlines()
return results
os_info_in.py:
通过导入刚刚编写的commands.py模块来获取Linux的OS版本号,内核版本号,以及当前的时间。
eachLine.strip()去掉eachLine前后的空格
findall('Description:\t#(.*)',afind)搜寻与正则表达式相匹配的内容
1 #!/usr/bin/env python
2 # coding=UTF-8
3 import commands
4 import re
5 class os_info_in:
def os_version(self):#获取linux的OS版本号
L_command = mands('lsb_release -a')
comm=L_command.excute_command()
allLine = []
for eachLine in comm:
allLine.append(eachLine.strip())
for afind in allLine:
if re.findall('Description:\t#(.*)',afind):
os_ver = re.findall('Description:\t#(.*)',afind)
def os_kernel(self):#获取linux的内核版本
L_command = mands('uname -r')
comm=L_command.excute_command()
allLine = []
for eachLine in comm:
allLine.append(eachLine.strip())
return allLine[0]
def os_date(self):#获取系统时间
L_command = mands('date')
comm=L_command.excute_command()
allLine = []
for eachLine in comm:
allLine.append(eachLine.strip())
return allLine[0]
linux_status.py:
保存获取到的linux状态信息
1 #!/usr/bin/env python
2 # coding=UTF-8
3 #保存linux状态信息
4 #os版本号:os_version
5 #内核版本号:os_kernal
6 #系统当前时间:os_date
7 class linux_status:
os_info.py:
通过os_info_in.py获取到的linux状态信息保存到专门储存状态信息的类linux_status中并返回
1 # coding=UTF-8
2 import linux_status
3 import os_info_in
4 class os_info:
def __init__(self):
self.linux_stat=linux_status.linux_status()
self.os_infos_in= os_info_in.os_info_in()
def os_info(self):
self.linux_stat.os_version = self.os_infos_in.os_version()
self.linux_stat.os_kernal = self.os_infos_in.os_kernel()
self.linux_stat.os_date = self.os_infos_in.os_date()
return self.linux_stat
linux_status_main.py:
测试主函数(打印所获取的信息)
1 #!/usr/bin/env python
2 # coding=UTF-8
3 import linux_status
4 import os_info
6 #linux版本,内核,时间
7 linux=linux_status.linux_status()
8 os= os_info.os_info()
9 linux=os.os_info()
10 print '系统:',linux.os_version
11 print '内核:',linux.os_kernal
12 print '时间:',linux.os_date
三、结果展示
由于刚刚接触Python语言,小程序刚刚写完感觉结构很冗余,分成一块一块的比较容易理解,感觉并不用把结果存进一个一个类里面,存到一个字典里面就可以(当时不是很熟悉字典),以后写的获取文件系统状态就是用的字典保存的,先写到这吧,慢慢写。。。
第一次写,希望大神多多提提意见~~~~~嘻嘻~~~~
阅读(...) 评论()&&&&前段时间写了一篇博文名为《利用脚本获取和的系统版本信息》,本篇博文利用这篇中的提供一个增强版本的获取信息的Python脚本。执行后,看起来就像登录 Linux系统时提示的motd信息一样,可以看到:系统的类型、发行版本(具体信息)、内核版本等当前系统的时间、时区系统每一个CPU核心的负载和CPU整体负载进程数量根分区的磁盘,Windows下默认C盘登录的用户总数和每一个登录到系统的用户的信息内存和交换分区的利用率默认网卡的系统启动时间和已运行时间运行截图如下:(1)Linux下截图:650) this.width=650;" src="/upload/images//301.jpg" style="float:" title="Linux System Status" alt="wKiom1h3O5PC0kNHAAST-VfrqOQ700.jpg-wh_50" />(2)Windows下截图:650) this.width=650;" src="/upload/images//302.jpg" style="float:" title="Windows System Status" alt="wKiom1h3O5TTnWReAAFqVnYsZjA784.jpg-wh_50" />Python代码如下:#!/usr/bin/python
#&encoding:&utf-8
#&-*-&coding:&utf8&-*-
Created&by&PyCharm.
File:&&&&&&&&&&&&&&&LinuxBashShellScriptForOps:getStatus.py
User:&&&&&&&&&&&&&&&Guodong
Create&Date:&&&&&&&&
Create&Time:&&&&&&&&15:32
import&platform
import&psutil
import&subprocess
import&sys
import&time
import&prettytable
mswindows&=&(sys.platform&==&"win32")&&#&learning&from&'subprocess'&module
linux&=&(sys.platform&==&"linux2")
def&getLocalIP():
&&&&import&netifaces
&&&&routingNicName&=&netifaces.gateways()['default'][netifaces.AF_INET][1]
&&&&for&&in&netifaces.interfaces():
&&&&&&&&if&interface&==&routingNicName:
&&&&&&&&&&&&try:
&&&&&&&&&&&&&&&&routingIPAddr&=&netifaces.ifaddresses(interface)[netifaces.AF_INET][0]['addr']
&&&&&&&&&&&&&&&&return&interface,&routingIPAddr
&&&&&&&&&&&&except&KeyError:
&&&&&&&&&&&&&&&&pass
def&getUser():
&&&&if&linux:
&&&&&&&&proc_obj&=&subprocess.Popen(r'tty',&shell=True,&stdout=subprocess.PIPE,
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&stderr=subprocess.STDOUT)
&&&&&&&&tty&=&municate()[0]
&&&&&&&&tty&=&[]
&&&&user_object&=&psutil.users()
&&&&for&login&in&user_object:
&&&&&&&&username,&login_tty,&login_host,&login_time&=&[suser&for&suser&in&login]
&&&&&&&&print&username,&login_tty,&login_host,&time.strftime('%b&%d&%H:%M:%S',&time.localtime(login_time)),
&&&&&&&&if&login_tty&in&tty:
&&&&&&&&&&&&print&'**current&user**'
&&&&&&&&else:
&&&&&&&&&&&&print
def&getTimeZone():
&&&&return&time.strftime("%Z",&time.gmtime())
def&getTimeNow():
&&&&now&=&time.strftime('%a&%b&%d&%H:%M:%S&%Y&%Z',&time.localtime(time.time()))
&&&&return&now
def&printHeader():
&&&&if&linux:
&&&&&&&&try:
&&&&&&&&&&&&with&open('/etc/issue')&as&f:
&&&&&&&&&&&&&&&&content&=&f.read().strip()
&&&&&&&&&&&&&&&&output_list&=&re.split(r'&\\',&content)
&&&&&&&&&&&&&&&&linux_type&=&list(output_list)[0]
&&&&&&&&except&IOError:
&&&&&&&&&&&&pass
&&&&&&&&else:
&&&&&&&&&&&&if&linux_type&is&not&None:
&&&&&&&&&&&&&&&&return&"Welcome&to&%s&(%s&%s&%s)\n&&System&information&as&of&%s"&%&(
&&&&&&&&&&&&&&&&&&&&linux_type,&platform.system(),&platform.release(),&platform.machine(),&getTimeNow()
&&&&&&&&&&&&&&&&)
&&&&&&&&&&&&else:
&&&&&&&&&&&&&&&&return
&&&&if&mswindows:
&&&&&&&&def&get_system_encoding():
&&&&&&&&&&&&import&codecs
&&&&&&&&&&&&import&locale
&&&&&&&&&&&&"""
&&&&&&&&&&&&The&encoding&of&the&default&system&locale&but&falls&back&to&the&given
&&&&&&&&&&&&fallback&encoding&if&the&encoding&is&unsupported&by&python&or&could
&&&&&&&&&&&&not&be&determined.&&See&tickets&#10335&and&#5846
&&&&&&&&&&&&"""
&&&&&&&&&&&&try:
&&&&&&&&&&&&&&&&encoding&=&locale.getdefaultlocale()[1]&or&'ascii'
&&&&&&&&&&&&&&&&codecs.lookup(encoding)
&&&&&&&&&&&&except&Exception:
&&&&&&&&&&&&&&&&encoding&=&'ascii'
&&&&&&&&&&&&return&encoding
&&&&&&&&DEFAULT_LOCALE_ENCODING&=&get_system_encoding()
&&&&&&&&import&_winreg
&&&&&&&&try:
&&&&&&&&&&&&reg_key&=&_winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,&"\\\\Windows&NT\\Current")
&&&&&&&&&&&&if&reg_key:
&&&&&&&&&&&&&&&&ProductName&=&_winreg.QueryValueEx(reg_key,&"ProductName")[0]&or&None
&&&&&&&&&&&&&&&&EditionId&=&_winreg.QueryValueEx(reg_key,&"EditionId")[0]&or&None
&&&&&&&&&&&&&&&&ReleaseId&=&_winreg.QueryValueEx(reg_key,&"ReleaseId")[0]&or&None
&&&&&&&&&&&&&&&&BuildLabEx&=&_winreg.QueryValueEx(reg_key,&"BuildLabEx")[0][:9]&or&None
&&&&&&&&&&&&&&&&return&"%s,&%s&[%s]\r\nVersion&%s&(OS&Internal&Version&%s)"&%&(
&&&&&&&&&&&&&&&&&&&&ProductName,&EditionId,&platform.version(),&ReleaseId,&BuildLabEx)
&&&&&&&&except&Exception&as&e:
&&&&&&&&&&&&print&e..decode(DEFAULT_LOCALE_ENCODING)
def&getHostname():
&&&&return&platform.node()
def&getCPU():
&&&&return&[x&/&100.0&for&x&in&psutil.cpu_percent(interval=0,&percpu=True)]
def&getLoadAverage():
&&&&if&linux:
&&&&&&&&import&multiprocessing
&&&&&&&&k&=&1.0
&&&&&&&&k&/=&multiprocessing.cpu_count()
&&&&&&&&if&os.path.exists('/proc/loadavg'):
&&&&&&&&&&&&return&[float(open('/proc/loadavg').read().split()[x])&*&k&for&x&in&range(3)]
&&&&&&&&else:
&&&&&&&&&&&&tokens&=&subprocess.check_output(['uptime']).split()
&&&&&&&&&&&&return&[float(x.strip(','))&*&k&for&x&in&tokens[-3:]]
&&&&if&mswindows:
&&&&&&&&#&print&psutil.cpu_percent()
&&&&&&&&#&print&psutil.cpu_times_percent()
&&&&&&&&#&print&psutil.cpu_times()
&&&&&&&&#&print&psutil.cpu_stats()
&&&&&&&&return&"%.2f%%"&%&psutil.cpu_percent()
def&getMemory():
&&&&v&=&psutil.virtual_memory()
&&&&return&{
&&&&&&&&'used':&v.total&-&v.available,
&&&&&&&&'free':&v.available,
&&&&&&&&'total':&v.total,
&&&&&&&&'percent':&v.percent,
def&getVirtualMemory():
&&&&v&=&psutil.swap_memory()
&&&&return&{
&&&&&&&&'used':&v.used,
&&&&&&&&'free':&v.free,
&&&&&&&&'total':&v.total,
&&&&&&&&'percent':&v.percent
def&getUptime():
&&&&uptime_file&=&"/proc/uptime"
&&&&if&os.path.exists(uptime_file):
&&&&&&&&with&open(uptime_file,&'r')&as&f:
&&&&&&&&&&&&return&f.read().split('&')[0].strip("\n")
&&&&&&&&return&time.time()&-&psutil.boot_time()
def&getUptime2():
&&&&boot_time&=&time.strftime("%Y-%m-%d&%H:%M:%S",&time.localtime(psutil.boot_time()))
&&&&print&"system&start&at:&%s"&%&boot_time,
&&&&uptime_total_seconds&=&time.time()&-&psutil.boot_time()
&&&&uptime_days&=&int(uptime_total_seconds&/&24&/&60&/&60)
&&&&uptime_hours&=&int(uptime_total_seconds&/&60&/&60&%&24)
&&&&uptime_minutes&=&int(uptime_total_seconds&/&60&%&60)
&&&&uptime_seconds&=&int(uptime_total_seconds&%&60)
&&&&print&"uptime:&%d&days&%d&hours&%d&minutes&%d&seconds"&%&(uptime_days,&uptime_hours,&uptime_minutes,&uptime_seconds)
&&&&user_number&=&len(psutil.users())
&&&&print&"%d&user:"&%&user_number
&&&&print&"&&\\"
&&&&for&user_tuple&in&psutil.users():
&&&&&&&&user_name&=&user_tuple[0]
&&&&&&&&user_terminal&=&user_tuple[1]
&&&&&&&&user_host&=&user_tuple[2]
&&&&&&&&user_login_time&=&time.strftime("%Y-%m-%d&%H:%M:%S",&time.localtime(user_tuple[3]))
&&&&&&&&print&"&&|-&user&online:&%s,&login&from&%s&with&terminal&%s&at&%s"&%&(
&&&&&&&&&&&&user_name,&user_host,&user_terminal,&user_login_time)
&&&&cpu_count&=&psutil.cpu_count()
&&&&&&&&with&open('/proc/loadavg',&'r')&as&f:
&&&&&&&&&&&&loadavg_c&=&f.read().split('&')
&&&&&&&&&&&&loadavg&=&dict()
&&&&&&&&&&&&if&loadavg_c&is&not&None:
&&&&&&&&&&&&&&&&loadavg['lavg_1']&=&loadavg_c[0]
&&&&&&&&&&&&&&&&loadavg['lavg_5']&=&loadavg_c[1]
&&&&&&&&&&&&&&&&loadavg['lavg_15']&=&loadavg_c[2]
&&&&&&&&&&&&&&&&loadavg['nr']&=&loadavg_c[3]
&&&&&&&&&&&&&&&&loadavg['last_pid']&=&loadavg_c[4]
&&&&&&&&print&"load&average:&%s,&%s,&%s"&%&(loadavg['lavg_1'],&loadavg['lavg_5'],&loadavg['lavg_15'])
&&&&&&&&if&float(loadavg['lavg_15'])&&&cpu_count:
&&&&&&&&&&&&print&"Note:&cpu&15&min&load&is&high!"
&&&&&&&&if&float(loadavg['lavg_5'])&&&cpu_count:
&&&&&&&&&&&&print&"Note:&cpu&5&min&load&is&high!"
&&&&&&&&if&float(loadavg['lavg_1'])&&&cpu_count:
&&&&&&&&&&&&print&"Note:&cpu&1&min&load&is&high!"
&&&&except&IOError:
&&&&&&&&pass
if&__name__&==&'__main__':
&&&&header&=&printHeader()
&&&&print&header
&&&&system_load&=&str(getLoadAverage()).strip("[]")
&&&&user_logged_in&=&len(psutil.users())
&&&&info_of_root_partition&=&psutil.disk_usage("/")
&&&&percent_of_root_partition_usage&=&"%.2f%%"&%&(
&&&&&&&&float(info_of_root_partition.used)&*&100&/&float(info_of_root_partition.total))
&&&&total_size_of_root_partition&=&"%.2f"&%&(float(psutil.disk_usage("/").total&/&1024)&/&1024&/&1024)
&&&&memory_info&=&getMemory()
&&&&memory_usage&=&"%.2f%%"&%&(float(memory_info['used'])&*&100&/&float(memory_info['total']))
&&&&swap_info&=&getVirtualMemory()
&&&&swap_usage&=&"%.2f%%"&%&(float(swap_info['used'])&*&100&/&float(swap_info['total']))
&&&&local_ip_address&=&getLocalIP()
&&&&table&=&prettytable.PrettyTable(border=False,&header=False,&left_padding_width=2)
&&&&table.field_names&=&["key1",&"value1",&"key2",&"value2"]
&&&&table.add_row(["System&load:",&system_load,&"Processes:",&len(list(psutil.process_iter()))])
&&&&table.add_row(["Usage&of&/:",&"%s&of&%sGB"&%&(percent_of_root_partition_usage,&total_size_of_root_partition),
&&&&&&&&&&&&&&&&&&&"Users&logged&in:",&user_logged_in])
&&&&table.add_row(["Memory&usage:",&memory_usage,&"IP&address&for&%s:"&%&local_ip_address[0],&local_ip_address[1]])
&&&&table.add_row(["Swap&usage:",&swap_usage,&"",&""])
&&&&for&field&in&table.field_names:
&&&&&&&&table.align[field]&=&"l"
&&&&print&table.get_string()
&&&&getUser()
&&&&getUptime2()注:脚本内容可以通过GitHub获取,/DingGuodong/LinuxBashShellScriptForOps/blob/master/functions/system/getSystemStatus.py,欢迎star、fork。已知存在问题:暂时未实现获取Windows下网卡的中文可视名称Windows下的tty名称默认为None,暂时没有设置对用户友好的显示Ubuntu Linux上motd信息的用户登录数量显示为同一用户同一个IP的多个用户视为同一用户,脚本中视为不同用户首次运行可能需要安装依赖的地方库,如psutil、platform、prettytable、netifaces等,请使用easy_install、pip、conda等安装。其他的因为时间原因未指出和未实现的问题,欢迎在文章下面评论留言和在GitHub上提issuetag:Python、Linux系统信息、Windows系统信息--end--本文出自 “通信,我的最爱” ,请务必保留此出处http://dgd2/1891468}

我要回帖

更多关于 python 获取系统时区 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信