Python入門–Datetime、TimeStamp、UTC、localtimeの相互変換する方法

1.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

2.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:
dt = dt + datetime.timedelta(hours=-8)
timestamp = total_seconds(dt – EPOCH)
return long(timestamp)
return dt
3.UTC時間のTimeStamp
def timestamp_utc_now():
return datetime2timestamp(datetime.datetime.utcnow())

4.local時間のTimeStamp
def timestamp_now():
return datetime2timestamp(datetime.datetime.now())

5.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

Posted by arkgame