pbootcms网站模板|日韩1区2区|织梦模板||网站源码|日韩1区2区|jquery建站特效-html5模板网

    1. <tfoot id='xwjP8'></tfoot>

        <bdo id='xwjP8'></bdo><ul id='xwjP8'></ul>

      <legend id='xwjP8'><style id='xwjP8'><dir id='xwjP8'><q id='xwjP8'></q></dir></style></legend>

      <small id='xwjP8'></small><noframes id='xwjP8'>

      <i id='xwjP8'><tr id='xwjP8'><dt id='xwjP8'><q id='xwjP8'><span id='xwjP8'><b id='xwjP8'><form id='xwjP8'><ins id='xwjP8'></ins><ul id='xwjP8'></ul><sub id='xwjP8'></sub></form><legend id='xwjP8'></legend><bdo id='xwjP8'><pre id='xwjP8'><center id='xwjP8'></center></pre></bdo></b><th id='xwjP8'></th></span></q></dt></tr></i><div class="5dhzt7h" id='xwjP8'><tfoot id='xwjP8'></tfoot><dl id='xwjP8'><fieldset id='xwjP8'></fieldset></dl></div>
    2. 使用 datetime 在 python 中獲取 UTC 時間戳

      get UTC timestamp in python with datetime(使用 datetime 在 python 中獲取 UTC 時間戳)

        <tbody id='3oma0'></tbody>
      <legend id='3oma0'><style id='3oma0'><dir id='3oma0'><q id='3oma0'></q></dir></style></legend>
        • <tfoot id='3oma0'></tfoot>

          <small id='3oma0'></small><noframes id='3oma0'>

            • <bdo id='3oma0'></bdo><ul id='3oma0'></ul>
            • <i id='3oma0'><tr id='3oma0'><dt id='3oma0'><q id='3oma0'><span id='3oma0'><b id='3oma0'><form id='3oma0'><ins id='3oma0'></ins><ul id='3oma0'></ul><sub id='3oma0'></sub></form><legend id='3oma0'></legend><bdo id='3oma0'><pre id='3oma0'><center id='3oma0'></center></pre></bdo></b><th id='3oma0'></th></span></q></dt></tr></i><div class="em8qgwo" id='3oma0'><tfoot id='3oma0'></tfoot><dl id='3oma0'><fieldset id='3oma0'></fieldset></dl></div>

                本文介紹了使用 datetime 在 python 中獲取 UTC 時間戳的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!

                問題描述

                有沒有辦法通過指定日期來獲取 UTC 時間戳?我的期望:

                Is there a way to get the UTC timestamp by specifying the date? What I would expect:

                datetime(2008, 1, 1, 0, 0, 0, 0)
                

                應該會導致

                 1199145600
                

                創建一個簡單的日期時間對象意味著沒有時區信息.如果我查看 datetime.utcfromtimestamp 的文檔,創建 UTC 時間戳意味著忽略時區信息.所以我猜想,創建一個天真的日期時間對象(就像我所做的那樣)會導致一個 UTC 時間戳.然而:

                Creating a naive datetime object means that there is no time zone information. If I look at the documentation for datetime.utcfromtimestamp, creating a UTC timestamp means leaving out the time zone information. So I would guess, that creating a naive datetime object (like I did) would result in a UTC timestamp. However:

                then = datetime(2008, 1, 1, 0, 0, 0, 0)
                datetime.utcfromtimestamp(float(then.strftime('%s')))
                

                結果

                2007-12-31 23:00:00
                

                datetime 對象中是否還有隱藏的時區信息?我做錯了什么?

                Is there still any hidden time zone information in the datetime object? What am I doing wrong?

                推薦答案

                樸素 datetime 與有意識 datetime

                Na?ve datetime versus aware datetime

                默認的 datetime 對象被稱為na?ve":它們保留時間信息而沒有時區信息.將樸素的 datetime 視為一個沒有明確來源的相對數字(即:+4)(實際上,您的來源在整個系統邊界中都很常見).

                Default datetime objects are said to be "na?ve": they keep time information without the time zone information. Think about na?ve datetime as a relative number (ie: +4) without a clear origin (in fact your origin will be common throughout your system boundary).

                相比之下,將感知 datetime 視為具有全球共同起源的絕對數字(即:8).

                In contrast, think about aware datetime as absolute numbers (ie: 8) with a common origin for the whole world.

                沒有時區信息,您無法將樸素"日期時間轉換為任何非樸素時間表示(如果我們不知道從哪里到哪里,+4 目標在哪里開始 ?).這就是為什么你不能有 datetime.datetime.toutctimestamp() 方法的原因.(參見:http://bugs.python.org/issue1457227)

                Without timezone information you cannot convert the "naive" datetime towards any non-naive time representation (where does +4 targets if we don't know from where to start ?). This is why you can't have a datetime.datetime.toutctimestamp() method. (cf: http://bugs.python.org/issue1457227)

                要檢查您的 datetime dt 是否幼稚,請檢查 dt.tzinfo,如果 None,那么它是天真:

                To check if your datetime dt is na?ve, check dt.tzinfo, if None, then it's na?ve:

                datetime.now()        ## DANGER: returns na?ve datetime pointing on local time
                datetime(1970, 1, 1)  ## returns na?ve datetime pointing on user given time
                

                我的約會時間很幼稚,我該怎么辦?

                您必須根據您的特定上下文做出假設:您必須問自己的問題是:您的 datetime 是 UTC 嗎?還是當地時間?

                You must make an assumption depending on your particular context: The question you must ask yourself is: was your datetime on UTC ? or was it local time ?

                • 如果您使用的是 UTC(您就沒有麻煩了):

                import calendar
                
                def dt2ts(dt):
                    """Converts a datetime object to UTC timestamp
                
                    naive datetime will be considered UTC.
                
                    """
                
                    return calendar.timegm(dt.utctimetuple())
                

              1. 如果您沒有使用 UTC,歡迎來到地獄.

                在使用前者之前,您必須使您的 datetime 不幼稚功能,通過將它們歸還給它們預期的時區.

                You have to make your datetime non-na?ve prior to using the former function, by giving them back their intended timezone.

                您需要時區名稱關于時區的信息如果 DST 在生成目標樸素日期時間時生效(角盒需要有關 DST 的最后信息):

                You'll need the name of the timezone and the information about if DST was in effect when producing the target na?ve datetime (the last info about DST is required for cornercases):

                import pytz     ## pip install pytz
                
                mytz = pytz.timezone('Europe/Amsterdam')             ## Set your timezone
                
                dt = mytz.normalize(mytz.localize(dt, is_dst=True))  ## Set is_dst accordingly
                

                不提供is_dst的后果:

                Consequences of not providing is_dst:

                不使用 is_dst 將生成不正確的時間(和 UTC 時間戳)如果在設置后向 DST 時生成了目標日期時間(例如通過刪除一小時來更改 DST 時間).

                Not using is_dst will generate incorrect time (and UTC timestamp) if target datetime was produced while a backward DST was put in place (for instance changing DST time by removing one hour).

                提供不正確的is_dst當然會產生不正確的時間(和 UTC 時間戳)僅在 DST 重疊或孔上.什么時候提供時間也不正確,發生在洞"中(由于時間不存在向前移動 DST),is_dst 將給出解釋如何考慮這個虛假時間,這是唯一的情況.normalize(..) 實際上會在這里做一些事情,因為它會將其翻譯為實際有效時間(更改日期時間和DST 對象(如果需要).注意 .normalize() 不是必需的最后有一個正確的 UTC 時間戳,但可能是如果你不喜歡在你的時間里有虛假時間的想法,推薦變量,特別是如果您在其他地方重復使用此變量.

                Providing incorrect is_dst will of course generate incorrect time (and UTC timestamp) only on DST overlap or holes. And, when providing also incorrect time, occuring in "holes" (time that never existed due to forward shifting DST), is_dst will give an interpretation of how to consider this bogus time, and this is the only case where .normalize(..) will actually do something here, as it'll then translate it as an actual valid time (changing the datetime AND the DST object if required). Note that .normalize() is not required for having a correct UTC timestamp at the end, but is probably recommended if you dislike the idea of having bogus times in your variables, especially if you re-use this variable elsewhere.

                避免使用以下內容:(參見:使用 pytz 進行日期時間時區轉換)

                dt = dt.replace(tzinfo=timezone('Europe/Amsterdam'))  ## BAD !!
                

                為什么?因為 .replace() 盲目地替換了 tzinfo 而沒有考慮到目標時間,會選擇一個壞的 DST 對象.而 .localize() 使用目標時間和您的 is_dst 提示選擇正確的 DST 對象.

                Why? because .replace() replaces blindly the tzinfo without taking into account the target time and will choose a bad DST object. Whereas .localize() uses the target time and your is_dst hint to select the right DST object.

                舊的錯誤答案(感謝@J.F.Sebastien 提出這個問題):

                OLD incorrect answer (thanks @J.F.Sebastien for bringing this up):

                希望,當您創建天真的 datetime 對象時,很容易猜測時區(您的本地來源),因為它與您希望不會在天真的日期時間之間更改的系統配置有關對象創建和您想要獲取 UTC 時間戳的時刻.這個技巧可以用來給出一個不完美的問題.

                Hopefully, it is quite easy to guess the timezone (your local origin) when you create your naive datetime object as it is related to the system configuration that you would hopefully NOT change between the naive datetime object creation and the moment when you want to get the UTC timestamp. This trick can be used to give an imperfect question.

                通過使用time.mktime,我們可以創建一個utc_mktime:

                By using time.mktime we can create an utc_mktime:

                def utc_mktime(utc_tuple):
                    """Returns number of seconds elapsed since epoch
                
                    Note that no timezone are taken into consideration.
                
                    utc tuple must be: (year, month, day, hour, minute, second)
                
                    """
                
                    if len(utc_tuple) == 6:
                        utc_tuple += (0, 0, 0)
                    return time.mktime(utc_tuple) - time.mktime((1970, 1, 1, 0, 0, 0, 0, 0, 0))
                
                def datetime_to_timestamp(dt):
                    """Converts a datetime object to UTC timestamp"""
                
                    return int(utc_mktime(dt.timetuple()))
                

                您必須確保您的 datetime 對象與創建您的 datetime 對象的時區在同一時區.

                You must make sure that your datetime object is created on the same timezone than the one that has created your datetime.

                最后一個解決方案是不正確的,因為它假設從現在開始的 UTC 偏移量與從 EPOCH 開始的 UTC 偏移量相同. 對于很多時區來說,情況并非如此(在特定時刻夏令時 (DST) 偏移量的年度最佳值).

                This last solution is incorrect because it makes the assumption that the UTC offset from now is the same than the UTC offset from EPOCH. Which is not the case for a lot of timezones (in specific moment of the year for the Daylight Saving Time (DST) offsets).

                這篇關于使用 datetime 在 python 中獲取 UTC 時間戳的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!

                【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!
              2. 相關文檔推薦

                python: Two modules and classes with the same name under different packages(python:不同包下同名的兩個模塊和類)
                Configuring Python to use additional locations for site-packages(配置 Python 以使用站點包的其他位置)
                How to structure python packages without repeating top level name for import(如何在不重復導入頂級名稱的情況下構造python包)
                Install python packages on OpenShift(在 OpenShift 上安裝 python 包)
                How to refresh sys.path?(如何刷新 sys.path?)
                Distribute a Python package with a compiled dynamic shared library(分發帶有已編譯動態共享庫的 Python 包)

                    <tbody id='vo97h'></tbody>
                      1. <small id='vo97h'></small><noframes id='vo97h'>

                      2. <tfoot id='vo97h'></tfoot>
                        • <bdo id='vo97h'></bdo><ul id='vo97h'></ul>

                          <i id='vo97h'><tr id='vo97h'><dt id='vo97h'><q id='vo97h'><span id='vo97h'><b id='vo97h'><form id='vo97h'><ins id='vo97h'></ins><ul id='vo97h'></ul><sub id='vo97h'></sub></form><legend id='vo97h'></legend><bdo id='vo97h'><pre id='vo97h'><center id='vo97h'></center></pre></bdo></b><th id='vo97h'></th></span></q></dt></tr></i><div class="wkkcqk0" id='vo97h'><tfoot id='vo97h'></tfoot><dl id='vo97h'><fieldset id='vo97h'></fieldset></dl></div>
                          <legend id='vo97h'><style id='vo97h'><dir id='vo97h'><q id='vo97h'></q></dir></style></legend>

                          主站蜘蛛池模板: 超声波焊接机_超音波熔接机_超声波塑焊机十大品牌_塑料超声波焊接设备厂家 | 光谱仪_积分球_分布光度计_灯具检测生产厂家_杭州松朗光电【官网】 | 乳化沥青设备_改性沥青设备_沥青加温罐_德州市昊通路桥工程有限公司 | 2-羟基泽兰内酯-乙酰蒲公英萜醇-甘草查尔酮A-上海纯优生物科技有限公司 | 北京中航时代-耐电压击穿试验仪厂家-电压击穿试验机 | 【德信自动化】点胶机_全自动点胶机_自动点胶机厂家_塑料热压机_自动螺丝机-深圳市德信自动化设备有限公司 | 六维力传感器_三维力传感器_二维力传感器-南京神源生智能科技有限公司 | 电车线(用于供电给电车的输电线路)-百科 | 层流手术室净化装修-检验科ICU改造施工-华锐净化工程-特殊科室建设厂家 | 南汇8424西瓜_南汇玉菇甜瓜-南汇水蜜桃价格 | 福兰德PVC地板|PVC塑胶地板|PVC运动地板|PVC商用地板-中国弹性地板系统专业解决方案领先供应商! 福建成考网-福建成人高考网 | 知网论文检测系统入口_论文查重免费查重_中国知网论文查询_学术不端检测系统 | 水质传感器_水质监测站_雨量监测站_水文监测站-山东水境传感科技有限公司 | 伊卡洛斯软装首页-电动窗帘,别墅窗帘,定制窗帘,江浙沪1000+别墅窗帘案例 | 细砂提取机,隔膜板框泥浆污泥压滤机,螺旋洗砂机设备,轮式洗砂机械,机制砂,圆锥颚式反击式破碎机,振动筛,滚筒筛,喂料机- 上海重睿环保设备有限公司 | 股票入门基础知识_股票知识_股票投资大师_格雷厄姆网 | 过跨车_过跨电瓶车_过跨转运车_横移电动平车_厂区转运车_无轨转运车 | 「安徽双凯」自动售货机-无人售货机-成人用品-自动饮料食品零食售货机 | 奇酷教育-Python培训|UI培训|WEB大前端培训|Unity3D培训|HTML5培训|人工智能培训|JAVA开发的教育品牌 | 专业深孔加工_东莞深孔钻加工_东莞深孔钻_东莞深孔加工_模具深孔钻加工厂-东莞市超耀实业有限公司 | 酵素生产厂家_酵素OEM_酵素加盟_酵素ODM_酵素原料厂家_厦门益力康 | 选矿设备,选矿生产线,选矿工艺,选矿技术-昆明昆重矿山机械 | 假肢-假肢价格-假肢厂家-河南假肢-郑州市力康假肢矫形器有限公司 | 企业微信scrm管理系统_客户关系管理平台_私域流量运营工具_CRM、ERP、OA软件-腾辉网络 | 分光色差仪,测色仪,反透射灯箱,爱色丽分光光度仪,美能达色差仪维修_苏州欣美和仪器有限公司 | 凝胶成像系统(wb成像系统)百科-上海嘉鹏 | 钢制拖链生产厂家-全封闭钢制拖链-能源钢铝拖链-工程塑料拖链-河北汉洋机械制造有限公司 | 扒渣机,铁水扒渣机,钢水扒渣机,铁水捞渣机,钢水捞渣机-烟台盛利达工程技术有限公司 | 无刷电机_直流无刷电机_行星减速机-佛山市藤尺机电设备有限公司 无菌检查集菌仪,微生物限度仪器-苏州长留仪器百科 | 智能家居全屋智能系统多少钱一套-小米全套价格、装修方案 | 国际高中-国际学校-一站式择校服务-远播国际教育 | 乐考网-银行从业_基金从业资格考试_初级/中级会计报名时间_中级经济师 | Win10系统下载_32位/64位系统/专业版/纯净版下载 | 一体化预制泵站-一体化提升泵站-一体化泵站厂家-山东康威环保 | 线粒体膜电位荧光探针-细胞膜-标记二抗-上海复申生物科技有限公司 | 罗氏牛血清白蛋白,罗氏己糖激酶-上海嵘崴达实业有限公司 | 合肥地磅_合肥数控切割机_安徽地磅厂家_合肥世佳电工设备有限公司 | 阻燃剂-氢氧化镁-氢氧化铝-沥青阻燃剂-合肥皖燃新材料 | 包装设计公司,产品包装设计|包装制作,包装盒定制厂家-汇包装【官方网站】 | 礼仪庆典公司,礼仪策划公司,庆典公司,演出公司,演艺公司,年会酒会,生日寿宴,动工仪式,开工仪式,奠基典礼,商务会议,竣工落成,乔迁揭牌,签约启动-东莞市开门红文化传媒有限公司 | 等离子表面处理机-等离子表面活化机-真空等离子清洗机-深圳市东信高科自动化设备有限公司 |