python常用モジュールのtimeとdatetime,random,os,sys,shutilについて簡単に説明します

7107 ワード

timeとdatetimeモジュール:Pythonでは、通常、時間を表す方法がいくつかあります.
  • タイムスタンプ(timestamp):通常、タイムスタンプは1970年1月1日00:00:00から秒単位で計算されるオフセット量を表します.「type(time.time()」を実行し、floatタイプを返します.
  • フォーマットされた時間文字列(Format String)
  • 構造化時間(struct_time):struct_timeメタグループには9つの要素があります.9つの要素があります.(年、月、日、時、分、秒、年の中で何週目、年の中で何日目、サマータイム)import time print(time.time()#タイムスタンプ:1487130156.419527 print(time.strftime("%Y-%m-%d%X"))print(time.localtime())#ローカルタイムゾーンのstruct_time print(time.gmtime()UTCタイムゾーンのstruct_time形式:%a Locale’s abbreviated weekday name.%A Locale’s full weekday name. %b Locale’s abbreviated month name. %B Locale’s full month name. %c Locale’s appropriate date and time representation. %d Day of the month as a decimal number [01,31]. %H Hour (24-hour clock) as a decimal number [00,23]. %I Hour (12-hour clock) as a decimal number [01,12]. %j Day of the year as a decimal number [001,366]. %m Month as a decimal number [01,12]. %M Minute as a decimal number [00,59]. %p Locale’s equivalent of either AM or PM. (1) %S Second as a decimal number [00,61]. (2) %U Week number of the year (Sunday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Sunday are considered to be in week 0. (3) %w Weekday as a decimal number [0(Sunday),6]. %W Week number of the year (Monday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Monday are considered to be in week 0. (3) %x Locale’s appropriate date representation. %X Locale’s appropriate time representation. %y Year without century as a decimal number [00,99]. %Y Year with century as a decimal number. %z Time zone offset indicating a positive or negative time difference from UTC/GMT of the form +HHMM or -HHMM, where H represents decimal hour digits and M represents decimal minute digits [-23:59, +23:59]. %Z Time zone name (no characters if no time zone exists). %% A literal ‘%’ character.

  • その中でコンピュータが認識する時間は「タイムスタンプ」形式にすぎないが、プログラマーが処理できる、あるいは人間が理解できる時間は「フォーマットされた時間文字列」、「構造化された時間」である.
    time.localtime()#      
    print(time.mktime(time.localtime()))#1473525749.0
    print(time.asctime())#Wed May  8 17:21:18 2019
    print(time.ctime()) #Wed May  8 17:21:55 2019
    time.sleep(1)#     
    

    datetimeモジュール
    print(datetime.datetime.now())#2019-05-08 17:24:47.045783
    print(datetime.datetime.now() +datetime.timedelta(days=10))
    print(datetime.datetime.now() +datetime.timedelta(days=10))#    10 
    print(datetime.datetime.now()+datetime.timedelta(hours=3))#    3  
    print(datetime.datetime.now()+datetime.timedelta(minutes=10))
    

    randomモジュール
    i
    mport random
    print(random.random())#      0-1   
    print(random.randint(1, 3))#    1-3   ,  1 3
    print(random.randrange(1,3))#    1-3   3   
    print(random.choice([1, 2, 3, 4]))#                
    print(random.sample([1,2,3,4],2))#               
    l=[1, 3, 4, 5]
    random.shuffle(l)#    。
    print(l)
    #             
    
    import random
    def make_code(n):
        res=''
        l=[]
        for i in range(10):
            l.append(str(i))
        for i in range(n):
            s1=chr(random.randint(65,90))
            s2=random.choice(l)
            res+=random.choice([s1,s2])
        return res
    print(make_code(5))
    

    osモジュール
    os.getcwd()は、現在のpythonスクリプトが動作するディレクトリパスosである現在の作業ディレクトリを取得する.chdir(「dirname」)は、現在のスクリプト作業ディレクトリを変更します.shell下cd osに相当する.curdirは現在のディレクトリを返します:(’.’)os.pardirは、現在のディレクトリの親ディレクトリ文字列名:(’...’)osを取得する.makedirs(‘dirname 1/dirname 2’)は、多層再帰ディレクトリosを生成することができる.removedirs(‘dirname 1’)ディレクトリが空の場合は削除し、上位ディレクトリに再帰する、空の場合は削除する、このようにos.mkdir(‘dirname’)は単段ディレクトリを生成する.shell中のmkdir dirname osに相当する.rmdir(‘dirname’)は単段空ディレクトリを削除し、ディレクトリが空でなければ削除できず、エラーを報告する.shell中のrmdir dirname osに相当する.Listdir(「dirname」)は、指定するディレクトリの下にあるすべてのファイルとサブディレクトリをリストし、非表示ファイルを含むosをリスト印刷する.remove()ファイルosを削除します.rename(「oldname」,「newname」)ファイル/ディレクトリosの名前を変更します.stat(‘path/filename’)は、ファイル/ディレクトリ情報osを取得する.sepはオペレーティングシステムの特定のパス区切り記号を出力、win下は""、Linux下は"/"os.linesepは現在のプラットフォームで使用する行終端子を出力し、win下は「t」、Linux下は「」osである.pathsep出力ファイルパスを分割するための文字列winの下には;Linuxの下は:os.name出力文字列は、現在プラットフォームが使用されていることを示します.win->‘nt’; Linux->‘posix’ os.System(「bash command」)shellコマンドを実行し、osを直接表示します.Environはシステム環境変数osを取得する.path.abspath(path)はpathが正規化する絶対経路osを返す.path.split(path)はpathをディレクトリとファイル名の二元グループに分割してosを返す.path.basename(path)はpathの最後のファイル名を返します.パスが/またはで終わると、空の値が返されます.すなわちos.path.split(path)の2番目の要素os.path.exists(path)pathが存在する場合、Trueを返します.パスが存在しない場合はFalse osに戻る.path.isabs(path)pathが絶対パスである場合はTrue osに戻る.path.isfile(path)pathが存在するファイルである場合、Trueを返します.そうでなければFalse osに戻ります.path.isdir(path)pathが存在するディレクトリである場合、Trueが返されます.そうでなければFalse osに戻ります.path.join(path 1[,path 2[,...]]))は複数のパスを組み合わせて返す、最初の絶対パスより前のパラメータはosを無視する.path.getatime(path)は、pathが指すファイルまたはディレクトリの最後のアクセス時間osを返す.path.getmtime(path)は、pathが指すファイルまたはディレクトリの最後の変更時間osを返す.path.getsize(path)はpathのサイズosを返す.path.dirname(path)はpathのディレクトリを返します.実はosです.path.split(path)の最初の要素
    Sysモジュール
    1 sys.argvコマンドラインパラメータリスト、最初の要素はプログラム自体のパス2 sysである.exit(n)プログラムを終了し、正常終了時exit(0)3 sys.バージョンはPython解釈プログラムのバージョン情報4 sysを取得する.MAxint最大のInt値5 sys.pathはモジュールの探索経路を返し、初期化時にPYTHONPATH環境変数の値6 sysを用いる.platformはオペレーティングシステムプラットフォーム名を返します
    shutilコピーファイル:
    import shutil
    shutil.copyfile("time_record","time_record1")
    #    ,time_record   time_record1
    shutil.copyfileobj(open('time_record','r'), open('time_record1', 'w'))#                 
    shutil.ignore_patterns(*patterns)
    shutil.copytree(src, dst, symlinks=False, ignore=None)
             
    shutil.copytree('folder1', 'folder2', ignore=shutil.ignore_patterns('*.pyc', 'tmp*')) #        ,   folder2            ,ignore       shutil.rmtree('folder1')
    shutil.copytree('f1', 'f2', symlinks=True, ignore=shutil.ignore_patterns('*.pyc', 'tmp*'))
    
    
             
        shutil.rmtree('folder1')
        shutil.move(src, dst)
            ,   mv  ,       
        shutil.move('folder1', 'folder3')
    

    shutil.make_archive(base_name, format,…)
    圧縮パッケージを作成し、zip、tarなどのファイルパスを返します.
    圧縮パッケージを作成し、zip、tarなどのファイルパスを返します.
    base_name:圧縮パッケージのファイル名、または圧縮パッケージのパスです.ファイル名のみの場合は、現在のディレクトリに保存します.そうでなければ、data_などの指定されたパスに保存します.bak=>現在のパスに保存:/tmp/data_bak=>保存先/tmp/format:圧縮パッケージの種類、zip、tar、bztar、gztar root_dir:圧縮するフォルダパス(デフォルト現在ディレクトリ)owner:ユーザー、デフォルト現在ユーザーgroup:グループ、デフォルト現在グループlogger:ログの記録に使用、通常logging.Loggerオブジェクト
    ret = shutil.make_archive("data_bak", 'gztar', root_dir='/data')
    

    #ファイルを圧縮パッケージに圧縮
    import zipfile
    import zipfile
    z=zipfile.ZipFile('my.zip','w')
    z.write('time_record')
    z.write("time_record1")
    

    import tarfile圧縮
     t=tarfile.open('/tmp/egon.tar','w')
     t.add('/test1/a.py',arcname='a.bak')
     t.add('/test1/b.py',arcname='b.bak')
     t.close()
    

    解凍
    t=tarfile.open('/tmp/egon.tar','r')
     t.extractall('/egon')
    t.close()