0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【忘備録】python datetime

Last updated at Posted at 2022-05-19

参考動画 https://www.udemy.com/course/python-beginner/learn/lecture/8459154?start=15#overview

import datetime

#現在時刻の出し方
now = datetime.datetime.now()
print(now)
#結果 2022-05-19 19:16:21.838450

#iso国際規格の時刻の出し方
print(now.isoformat())
#結果 2022-05-19T19:16:21

#オリジナルの時刻の出し方
print(now.strftime('%d/%m/%y'))
#結果 19/05/22

#年月日だけあつかう場合
today = datetime.date.today()
print(today)
#結果 2022-05-19

#自分で設定した時刻をマイクロセカンドまで表示する場合
t = datetime.time(hour=1,minute=10,second=5,microsecond=100 )
print(t)
#結果 01:10:05.000100

# ~週間前を求める場合
d = datetime.timedelta(weeks=-1)
print(now +d)
# 結果 2022-05-12 19:25:40.272399

# 1年前を求める場合
d = datetime.timedelta(days=-365)
print(now +d)
# 結果 2021-05-19 19:30:17.314440

# ~秒か後の表示させる場合
import time
print('###')
time.sleep(2)
print('####')

#時刻をバックアップファイルに組み込む場合

import os
import shutil

file_name = 'text.txt'
if os.path.exists(file_name):
    shutil.copy(file_name,"{}.{}".format(
        file_name, now.strftime('%Y_%m_%d_$H_$M_$S')
    ))

with open(file_name, 'w') as f:
    f.write('test')
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?