unixtime⇔datetimeの変換
import datetime
now = datetime.datetime.now()
unixtime = int(now.strftime('%s'))
datetime.datetime.fromtimestamp(unixtime)
datetime⇔strの変換
import datetime
date_str = '2018/2/1 12:30'
date_dt = datetime.datetime.strptime(date_str, '%Y/%m/%d %H:%M')
print(date_dt)
dt_now = datetime.datetime.now()
print(dt_now.strftime('%Y-%m-%d %H:%M:%S'))
boto3でデフォルト以外のprofileを使う
import boto3
from boto3.session import Session
profile = 'hoge'
session = Session(profile_name=profile)
配列のループをindexと一緒に
teams = ["Packers", "49ers", "Ravens", "Patriots"]
for index, team in enumerate(teams):
print index, team
>>> 0 Packers
>>> 1 49ers
>>> 2 Ravens
>>> 3 Patriots
2つの配列を同時にループ
nfc = ["Packers", "49ers"]
afc = ["Ravens", "Patriots"]
for teama, teamb in zip(nfc, afc):
print teama + " vs. " + teamb
>>> Packers vs. Ravens
>>> 49ers vs. Patriots
match
import re
pattern = r"ca"
text = "caabsacasca"
matchOB = re.match(pattern , text)
if matchOB:
print matchOB.group()
search
pattern = r"ca"
text = "caabsacasca"
matchOB = re.search(pattern , text)
if matchOB:
print(matchOB)
print(matchOB.group())
print(matchOB.start())
print(matchOB.end())
print(matchOB.span())
ロギング
import logging
from logging import getLogger, StreamHandler, Formatter
logger = getLogger("Log")
logger.setLevel(logging.DEBUG)
stream_handler = StreamHandler()
stream_handler.setLevel(logging.DEBUG)
handler_format = Formatter('[%(levelname)s]\t%(asctime)s : %(message)s')
stream_handler.setFormatter(handler_format)
logger.addHandler(stream_handler)
logger.error("ERROR")
logger.warning("WARN")
logger.info("INFO")
logger.debug("DEBUG")
ファイル操作
ファイル読み込み
file_name = 'hoge.csv'
with open(file_name) as f:
for line in f:
cols = line.split(",")
print(cols[0].strip())
- strip()しないと、最後のカラムに改行も含まれてしまう。
ファイル書き込み
file_name = 'dest.txt'
with open(file_name, mode='w') as f:
f.write(s)