物理の駅 Physics station by 現役研究者

テクノロジーは共有されてこそ栄える

Python 時間をdatetime型、文字列、unixtimeに相互変換

文字列→datetime, unixtime, 文字列

import datetime

tstr = '2020/9/17 9:00:01'
tdt = datetime.datetime.strptime(tstr, '%Y/%m/%d %H:%M:%S')
d_week = {'Sun':'日','Mon':'月','Tue':'火','Wed':'水','Thu':'木','Fri':'金','Sat':'土'}
print(type(tdt))
print(tdt)
print(tdt.timestamp())
print(tdt.strftime('%Y年%m月%d日({}) %H時%M分%S秒').format(d_week[tdt.strftime('%a')]))
print(tdt.strftime('%Y/%m/%d %H:%M:%S'))

unixtime→datetime, unixtime, 文字列

import datetime

tdt = datetime.datetime.fromtimestamp(1600300801.0)
d_week = {'Sun':'日','Mon':'月','Tue':'火','Wed':'水','Thu':'木','Fri':'金','Sat':'土'}
print(type(tdt))
print(tdt)
print(datetime.datetime.timestamp(tdt))
print(tdt.strftime('%Y年%m月%d日({}) %H時%M分%S秒').format(d_week[tdt.strftime('%a')]))
print(tdt.strftime('%Y/%m/%d %H:%M:%S'))

datetime→datetime, unixtime, 文字列

import datetime

tdt = datetime.datetime(2022, 9, 17, 9, 0, 1)
d_week = {'Sun':'日','Mon':'月','Tue':'火','Wed':'水','Thu':'木','Fri':'金','Sat':'土'}
print(type(tdt))
print(tdt)
print(datetime.datetime.timestamp(tdt))
print(tdt.strftime('%Y年%m月%d日({}) %H時%M分%S秒').format(d_week[tdt.strftime('%a')]))
print(tdt.strftime('%Y/%m/%d %H:%M:%S'))

出力

<class 'datetime.datetime'>
2022-09-17 09:00:01
1663372801.0
2022年09月17日(土) 09時00分01秒
2022/09/17 09:00:01

現在時刻から

tdt = datetime.datetime.now()

matplotlibで時間のフォーマットを変える

import matplotlib.dates as mdates
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%d日%H時'))

ツイッター用

dt = datetime.datetime.strptime(data["created_at"],'%a %b %d %H:%M:%S %z %Y')
JST = datetime.timezone(datetime.timedelta(hours=9), "JST")
dt = dt.astimezone(JST)
diff_days = (datetime.datetime.now(JST)-dt).days

import datetime

#tweet IDをタイムスタンプに
def tweet_id2timestamp(tweet_id):
    return ((tweet_id >> 22) + 1288834974657) / 1000

#tweet IDをdatetimeに
def tweet_id2time(tweet_id):
    return datetime.datetime.fromtimestamp(tweet_id2timestamp(tweet_id))

#datetimeをtweet_idに
def time2tweet_id(dt):
    return timestamp2tweet_id(dt.timestamp())

#timestampをtweet_idに
def timestamp2tweet_id(timestamp):
    return (round(timestamp*1000)-1288834974657)<<22

その日が月末かどうかを判定する方法

import datetime

def is_end_of_month(date):
    first_day_of_month = date + datetime.timedelta(days=1)
    return date.month != first_day_of_month.month

date1 = datetime.datetime(2021, 12, 31) #年末
date2 = datetime.datetime(2020, 2, 29) #閏年
date3 = datetime.datetime(2022, 3, 15) #普通の日

print(is_end_of_month(date1))
print(is_end_of_month(date2))
print(is_end_of_month(date3))

検索ワード: 曜日