1. 程式人生 > >純python處理時區的轉換

純python處理時區的轉換

首先要明白python的datetime物件有兩種型別,而Python的datetime可以處理2種類型的時間,分別為offset-naive和offset-aware。前者是指沒有包含時區資訊的時間,後者是指包含時區資訊的時間,只有同類型的時間才能進行減法運算和比較。

#-*- coding=cp936 -*-
from datetime import timedelta,tzinfo
import datetime

ZERO_TIME_DELTA = timedelta(0)
LOCAL_TIME_DELTA = timedelta(hours=8) # 本地時區偏差

class UTC(tzinfo):
    """實現了格林威治的tzinfo類"""
    def utcoffset(self, dt):
        return ZERO_TIME_DELTA

    def dst(self, dt):
        return ZERO_TIME_DELTA

class LocalTimezone(tzinfo):
    """實現北京時間的類"""
    def utcoffset(self, dt):
        return LOCAL_TIME_DELTA

    def dst(self, dt):
        return ZERO_TIME_DELTA

    def tzname(self, dt):    #tzname需要返回時區名
        return '+08:00'

print datetime.datetime.now(UTC())    #UTC時間  差八個小時
print datetime.datetime.now(LocalTimezone())   #根據本地  時區 生成offset-aware類的datetime物件
print type(datetime.datetime.now(LocalTimezone()))

print datetime.datetime.now()    #北京時間       一旦生成了一個offset-naive型別的datetime物件
print datetime.datetime.now().replace(tzinfo=UTC())   #   呼叫replace(tzinfo=UTC())即可轉換成offset-aware型別


print datetime.datetime.now().replace(tzinfo=LocalTimezone()).astimezone(UTC())   #時區轉換,


print '----------------------------------------------'
print datetime.datetime.utcnow()
#講一個 已知時區的datetime類轉換成UTC()的日期
datetime_test = datetime.datetime(2013,10,23,20,44,11).replace(tzinfo=LocalTimezone()).astimezone(UTC())
print datetime_test
print '---------------------------------'

結果:

2014-02-19 07:38:07.328000+00:00
2014-02-19 15:38:07.328000+08:00
<type 'datetime.datetime'>
2014-02-19 15:38:07.328000
2014-02-19 15:38:07.328000+00:00
2014-02-19 07:38:07.328000+00:00
----------------------------------------------
2014-02-19 07:38:07.328000
2013-10-23 12:44:11+00:00
---------------------------------

相關推薦

python處理時區轉換

首先要明白python的datetime物件有兩種型別,而Python的datetime可以處理2種類型的時間,分別為offset-naive和offset-aware。前者是指沒有包含時區資訊的時間,後者是指包含時區資訊的時間,只有同類型的時間才能進行減法運算和比較。

Python日期時區轉換

獲取當前UTC時間: utc_now = datetime.utcnow().replace(tzinfo=timezone.utc) print(utc_now) 2018-09-25 01:11

python處理矩陣:對矩陣進行轉置

方法一 :使用常規的思路 def transpose(M): # 初始化轉置後的矩陣 result = [] # 獲取轉置前的行和列 row, col = shape(

python處理datetime型別的時區轉換

需求:資料庫庫中的資料是按照UTC時間進行儲存 所以取出來顯示給使用者 需要處理一下時區 關於pytz包:http://pytz.sourceforge.net/ >>>import pytz, datetime >>>tz0 = py

python處理時間格式轉換,將xxxx年xx月xx日轉化為xxxx-xx-xx格式

publish_Time = "2018年10月10日" array = time.strptime(publish_Time, u"%Y年%m月%d日") try: publishTime = time.strftime("%Y-%m-%d", array) except Ex

Java中處理時區轉換

最近在抓英國博彩網站的資料,他們給出的時間都是格林威治時間,我們需要轉換為中國時間才能使用,這裡要用到Java裡的TimeZone介面。 通過下面的程式碼即可進行轉換。 TimeZone timeZone = TimeZone.getTimeZone("

python處理圖片---通道轉換、裁剪與幾何變換

                   用python處理圖片---通道轉換、裁剪與幾何變換 1、彩色影象轉灰度圖 轉載:https://www.cnblogs.com/denny402/p/5

時區轉換

local strong consola nbsp 本地 時間轉換 spa server tostring 工作中遇到的問題,服務器在美國,但是客戶在印度,所以要把本地時間/服務器時間轉換成印度時間。代碼如下: 將本地時區轉換成印度時區: String indianTi

python處理Excel

表名 格式 xls 常用操作 問題 進行 pre work times 1,xlrd xlrd是用來從Excel中讀寫數據的,但我平常只用它進行讀操作,寫操作會遇到些問題。用xlrd進行讀取比較方便,流程和平常手動操作Excel一樣,打開工作簿(Workbook),選擇工作

CAD軟件中的批處理CAD轉換怎麽使用

  大家都是知道格式之間的轉換,也知道CAD轉PDF,CAD轉JPEG等格式的轉換。那麽你們知道批量轉換嗎,如果要轉換多的文件就可以使用CAD軟件的批處理,那麽是如何操作的了,下面我們去了解一下吧。 其實通過使用CAD相關的軟件就可以解決各種難題,接下來通過“迅捷CAD轉PDF轉換器”跟大家分享應該如何將應

Python中將dict轉換為kwargs

war 我們 convert quest ssi ref dict pytho ons Python中將dict轉換為kwargs 我們都知道kwargs是變長kv參數,能否將dict轉換成kwargs。 在python調用函數的時候func(**{‘type‘=‘ev

第三篇.python 編碼的轉換

utf-8 python3 python2 第三篇 pytho pan span 需要 enc !/usr/bin/python2# -*- coding:utf-8 -*-temp = "豬"#解碼,需要指定原來是什麽編碼,解碼成Unicodetemp_unicode =

Python處理微信利器——itchat

主頁 chat cnblogs 微信 tle 博客 處理 pytho 信息 接觸itchat是一個偶然,上知乎刷出一個有意思的文章。於是乎運行源碼,調錯加上查閱博客,發現itchat大有可為。 知乎鏈接:https://zhuanlan.zhihu.com/p/257829

Python 將IP轉換為int

soc main spa == style print int 127.0.0.1 toa import socket import struct if __name__ == ‘__main__‘: ip = ‘127.0.0.1‘ int

[ZZ] 如何在多版本anaconda python環境下轉換spyder

過程 pda 名稱 -- idt anaconda rip gin div https://www.zhihu.com/people/alexwhu/answers 使用anaconda的話,可以參考以下步驟: 1、打開anaconda navigator

Python〗-- 編碼轉換

mage 韓文 國家 跳板 def odin bsp unicode color 【字符編碼與轉碼】 為什麽要進行編碼和轉碼 由於每個國家電腦的字符編碼格式不統一(列中國:GBK),同一款軟件放到不同國家的電腦上會出現亂碼的情況,出現這種情況如何解決呢?! 當然由於所有國家

python的強制轉換(當出現 not supported between instances of 'str' and 'int' 的錯誤時)

int typeerror error: 有時 ror images blog 整型 bsp 當我們編程時,有時會出現如下錯誤:TypeError: ‘>‘ not supported between instances of ‘str‘ and ‘int‘ 如下圖:

Python腳本轉換成windows的可執行程序

擴展 red pack 傳遞 bsp evel packages c++ scrip 一、簡介 py2exe是一個將python腳本轉換成windows上的可獨立執行的可執行程序(*.exe)的工具,這樣,你就可以不用裝python而在windows系統上運行這個可執行程序

python--處理數據

步長 四則運算 一個 step 操作數 命名 換行 變量名 對象 一、數據類型: 定義:按照python規定的格式,把數據的類型告知python; 賦值:定義好的數據,傳遞給變量的過程; 變量:數據賦值的對象,通過變量去操作數據; 變量名命名規則: 1、a-z,A-Z,數字