検索
ホームページバックエンド開発Python チュートリアルPython中实现对Timestamp和Datetime及UTC时间之间的转换

Python项目中很多时候会需要将时间在Datetime格式和TimeStamp格式之间转化,又或者你需要将UTC时间转化为本地时间,本文总结了这几个时间之间转化的函数,供大家参考。

一、Datetime转化为TimeStamp
 

def datetime2timestamp(dt, convert_to_utc=False):
  ''' Converts a datetime object to UNIX timestamp in milliseconds. '''
  if isinstance(dt, datetime.datetime):
    if convert_to_utc: # 是否转化为UTC时间
      dt = dt + datetime.timedelta(hours=-8) # 中国默认时区
    timestamp = total_seconds(dt - EPOCH)
    return long(timestamp)
  return dt

二、TimeStamp转化为Datetime
 

def timestamp2datetime(timestamp, convert_to_local=False):
  ''' Converts UNIX timestamp to a datetime object. '''
  if isinstance(timestamp, (int, long, float)):
    dt = datetime.datetime.utcfromtimestamp(timestamp)
    if convert_to_local: # 是否转化为本地时间
      dt = dt + datetime.timedelta(hours=8) # 中国默认时区
    return dt
  return timestamp

三、当前UTC时间的TimeStamp
 

def timestamp_utc_now():
  return datetime2timestamp(datetime.datetime.utcnow())

四、当前本地时间的TimeStamp
 

def timestamp_now():
  return datetime2timestamp(datetime.datetime.now())

五、UTC时间转化为本地时间
 

# 需要安装python-dateutil
# Ubuntu下:sudo apt-get install python-dateutil
# 或者使用PIP:sudo pip install python-dateutil
from dateutil import tz
from dateutil.tz import tzlocal
from datetime import datetime
 
# get local time zone name
print datetime.now(tzlocal()).tzname()
 
# UTC Zone
from_zone = tz.gettz('UTC')
# China Zone
to_zone = tz.gettz('CST')
 
utc = datetime.utcnow()
 
# Tell the datetime object that it's in UTC time zone
utc = utc.replace(tzinfo=from_zone)
 
# Convert time zone
local = utc.astimezone(to_zone)
print datetime.strftime(local, "%Y-%m-%d %H:%M:%S")

声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
Python:コンパイラまたはインタープリター?Python:コンパイラまたはインタープリター?May 13, 2025 am 12:10 AM

Pythonは解釈された言語ですが、コンパイルプロセスも含まれています。 1)Pythonコードは最初にBytecodeにコンパイルされます。 2)ByteCodeは、Python Virtual Machineによって解釈および実行されます。 3)このハイブリッドメカニズムにより、Pythonは柔軟で効率的になりますが、完全にコンパイルされた言語ほど高速ではありません。

ループvs whileループ用のpython:いつ使用するか?ループvs whileループ用のpython:いつ使用するか?May 13, 2025 am 12:07 AM

useaforloopwhenteratingoverasequenceor foraspificnumberoftimes; useawhileloopwhentinuninguntinuntilaConditionismet.forloopsareidealforknownownownownownownoptinuptinuptinuptinuptinutionsituations whileoopsuitsituations withinterminedationations。

Pythonループ:最も一般的なエラーPythonループ:最も一般的なエラーMay 13, 2025 am 12:07 AM

pythonloopscanleadtoErrorslikeinfiniteloops、ModifiningListsDuringiteration、Off-Oneerrors、Zero-dexingissues、およびNestededLoopinefficiencies.toavoidhese:1)use'i

ループの場合、およびPythonのループ:それぞれの利点は何ですか?ループの場合、およびPythonのループ:それぞれの利点は何ですか?May 13, 2025 am 12:01 AM

forloopsareadvastountousforknowterations and sequences、offeringsimplicityandeadability;

Python:編集と解釈に深く掘り下げますPython:編集と解釈に深く掘り下げますMay 12, 2025 am 12:14 AM

pythonusesahybridmodelofcompilation andtertation:1)thepythoninterpretercompilessourcodeodeplatform-indopent bytecode.2)thepythonvirtualmachine(pvm)thenexecuteTesthisbytecode、balancingeaseoputhswithporformance。

Pythonは解釈されたものですか、それとも編集された言語であり、なぜそれが重要なのですか?Pythonは解釈されたものですか、それとも編集された言語であり、なぜそれが重要なのですか?May 12, 2025 am 12:09 AM

pythonisbothintersedand compiled.1)it'scompiledtobytecode forportabalityacrossplatforms.2)bytecodeisthenは解釈され、開発を許可します。

ループ対pythonのループの場合:説明されたキーの違いループ対pythonのループの場合:説明されたキーの違いMay 12, 2025 am 12:08 AM

loopsareideal whenyouwhenyouknumberofiterationsinadvance、foreleloopsarebetterforsituationsは、loopsaremoreedilaConditionismetを使用します

ループのために:実用的なガイドループのために:実用的なガイドMay 12, 2025 am 12:07 AM

henthenumber ofiterationsisknown advanceの場合、dopendonacondition.1)forloopsareideal foriterating over for -for -for -saredaverseversives likelistorarrays.2)whileopsaresupasiable forsaresutable forscenarioswheretheloopcontinupcontinuspificcond

See all articles

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

Video Face Swap

Video Face Swap

完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

ホットツール

VSCode Windows 64 ビットのダウンロード

VSCode Windows 64 ビットのダウンロード

Microsoft によって発売された無料で強力な IDE エディター

WebStorm Mac版

WebStorm Mac版

便利なJavaScript開発ツール

mPDF

mPDF

mPDF は、UTF-8 でエンコードされた HTML から PDF ファイルを生成できる PHP ライブラリです。オリジナルの作者である Ian Back は、Web サイトから「オンザフライ」で PDF ファイルを出力し、さまざまな言語を処理するために mPDF を作成しました。 HTML2FPDF などのオリジナルのスクリプトよりも遅く、Unicode フォントを使用すると生成されるファイルが大きくなりますが、CSS スタイルなどをサポートし、多くの機能強化が施されています。 RTL (アラビア語とヘブライ語) や CJK (中国語、日本語、韓国語) を含むほぼすべての言語をサポートします。ネストされたブロックレベル要素 (P、DIV など) をサポートします。

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Eclipse を SAP NetWeaver アプリケーション サーバーと統合します。

メモ帳++7.3.1

メモ帳++7.3.1

使いやすく無料のコードエディター