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")

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

useaforloopwhenteratingoverasequenceor foraspificnumberoftimes; useawhileloopwhentinuninguntinuntilaConditionismet.forloopsareidealforknownownownownownownoptinuptinuptinuptinuptinutionsituations whileoopsuitsituations withinterminedationations。

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

forloopsareadvastountousforknowterations and sequences、offeringsimplicityandeadability;

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

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

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

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


ホットAIツール

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

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

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

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

人気の記事

ホットツール

VSCode Windows 64 ビットのダウンロード
Microsoft によって発売された無料で強力な IDE エディター

WebStorm Mac版
便利なJavaScript開発ツール

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
Eclipse を SAP NetWeaver アプリケーション サーバーと統合します。

メモ帳++7.3.1
使いやすく無料のコードエディター
