欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Python datetime time os模块 常用操作

程序员文章站 2022-07-10 13:40:04
...

Python datetime time 常用操作

参考:http://www.cnblogs.com/zhangbo127/p/4548898.html
http://blog.csdn.net/google19890102/article/details/51355282
http://www.oschina.net/code/snippet_736230_26816
root@kali:~/python/laowangpy/function# cat kt1401time.py 
#!/usr/bin/python
# --*-- coding:utf-8 --*--

import time
import datetime

now1 = time.strftime("%Y-%m-%d %H:%M:%S")#打印当前时间的第一种方式
print "当前时间:" 
print now1

now2 = datetime.datetime.now()#打印当前时间的第二种方式
print "当前时间:" 
print now2

d = datetime.datetime.now()

def day_get(d):
    oneday = datetime.timedelta(days=1)
    day = d - oneday
    date_from = datetime.datetime(day.year, day.month, day.day, 0, 0, 0)
    date_to = datetime.datetime(day.year, day.month, day.day, 23, 59, 59)
    print "前一天时间:"
    print '---'.join([str(date_from), str(date_to)])

def week_get(d):
    dayscount = datetime.timedelta(days=d.isoweekday())
    dayto = d - dayscount
    sixdays = datetime.timedelta(days=6)
    dayfrom = dayto - sixdays
    date_from = datetime.datetime(dayfrom.year, dayfrom.month, dayfrom.day, 0, 0, 0)
    date_to = datetime.datetime(dayto.year, dayto.month, dayto.day, 23, 59, 59)
    print "前一周的时间:"
    print '---'.join([str(date_from), str(date_to)])

def month_get(d):
    dayscount = datetime.timedelta(days=d.day)
    dayto = d - dayscount
    date_from = datetime.datetime(dayto.year, dayto.month, 1, 0, 0, 0)
    date_to = datetime.datetime(dayto.year, dayto.month, dayto.day, 23, 59, 59)
    print "前一个月的时间:"
    print '---'.join([str(date_from), str(date_to)])

day_get(d)
week_get(d)
month_get(d)
root@kali:~/python/laowangpy/function# 
root@kali:~/python/laowangpy/function# 
root@kali:~/python/laowangpy/function# 
root@kali:~/python/laowangpy/function# 
root@kali:~/python/laowangpy/function# python kt1401time.py 
当前时间:
2017-11-27 21:05:41
当前时间:
2017-11-27 21:05:41.831439
前一天时间:
2017-11-26 00:00:00---2017-11-26 23:59:59
前一周的时间:
2017-11-20 00:00:00---2017-11-26 23:59:59
前一个月的时间:
2017-10-01 00:00:00---2017-10-31 23:59:59
root@kali:~/python/laowangpy/function# 

习题二:
1 用os模块的方法完成ping www.baidu.com 操作。
2 定义一个函数kouzhang(dirpwd),用os模块的相关方法,返回一个列表,列表包括:dirpwd路径下所有文件不重复的扩展名,如果有2个”.py”的扩展名,则返回一个”.py”。

>>> import os
>>> os.system("ls -la")
总用量 92
drwxr-xr-x 3 root root 4096 1119 21:07 .
drwxr-xr-x 6 root root 4096 111 21:47 ..
-rw-r--r-- 1 root root  165 114 13:53 01funcmaxmin.py
-rw-r--r-- 1 root root  555 116 21:01 02funcmaxchar.py
-rw-r--r-- 1 root root  250 116 21:08 03gethelpmodule2.py
-rw-r--r-- 1 root root  283 114 16:25 03gethelpmodule.py
-rw-r--r-- 1 root root  184 115 10:12 04pathwin.py
-rw-r--r-- 1 root root  453 115 10:55 05getdirfolder.py
-rw-r--r-- 1 root root  131 111 22:19 fuc_add.py
-rw-r--r-- 1 root root  180 111 22:07 fuc_name_1.py
-rw-r--r-- 1 root root  193 114 09:42 funvar1.py
-rw-r--r-- 1 root root  102 114 09:56 funvar2.py
-rw-r--r-- 1 root root  350 114 09:56 funvar3.py
-rw-r--r-- 1 root root  289 116 22:35 k301_code.py
-rw-r--r-- 1 root root  162 116 22:50 k302_arge.py
-rw-r--r-- 1 root root  248 116 22:57 k303_arge2.py
-rw-r--r-- 1 root root  342 1119 13:56 k501lambda.py
-rw-r--r-- 1 root root 2029 1119 21:07 kt1101class.py
drwxr-xr-x 3 root root 4096 1119 22:07 testm
-rw-r--r-- 1 root root  567 1118 12:02 xt0301oushu.py
-rw-r--r-- 1 root root  378 1118 12:30 xt0302url.py
-rw-r--r-- 1 root root  505 1118 20:18 xt0303mutilist.py
-rw-r--r-- 1 root root  184 1118 20:19 xt0501filter.py
0
>>>

>>> os.system("ping www.baidu.com")
PING www.a.shifen.com (14.215.177.39) 56(84) bytes of data.
64 bytes from 14.215.177.39: icmp_req=1 ttl=128 time=101 ms
64 bytes from 14.215.177.39: icmp_req=2 ttl=128 time=9.18 ms
64 bytes from 14.215.177.39: icmp_req=3 ttl=128 time=9.95 ms
64 bytes from 14.215.177.39: icmp_req=4 ttl=128 time=14.5 ms
64 bytes from 14.215.177.39: icmp_req=5 ttl=128 time=9.47 ms
64 bytes from 14.215.177.39: icmp_req=6 ttl=128 time=9.17 ms
64 bytes from 14.215.177.39: icmp_req=7 ttl=128 time=9.41 ms
64 bytes from 14.215.177.39: icmp_req=8 ttl=128 time=9.45 ms
64 bytes from 14.215.177.39: icmp_req=9 ttl=128 time=10.8 ms
64 bytes from 14.215.177.39: icmp_req=10 ttl=128 time=9.18 ms
^Z
[1]+  已停止               python
[email protected]:~/python/laowangpy/function#
root@kali:~/python/laowangpy/function# cat tt.py 
#!/usr/bin/python
# --*-- coding:utf-8 --*--

import os

def kuozhan(dirpwd):
    if os.path.isdir(dirpwd):#如果是目录,则进入
        listdir = os.listdir(dirpwd)
        #print listdir#打印目录下所有文件,并成为列表
        for k in listdir:
            if os.path.isfile(k):#判断是否文件,是则进入
                #print "------------------------------------"
                #print k#打印文件
                result.add(os.path.splitext(k)[1])#把每个文件的扩展名加入列表result中
                #print "+++++++++++++++++++"
                #print os.path.splitext(k)[1]#打印每个文件的扩展名
            else:
                kuozhan(k)#判断是否为文件夹,是则进入循环
     else:#不是目录,即是文件的话,则进入
        result.add(os.path.splitext(dirpwd)[1])#直接分离文件名与扩展名;默认返回(fname,fextension)元组,可做分片操作,fname为文件的绝对路径,fextension文件的扩展名

result = set()#对列表result中所有信息进行去重处理
kuozhan(os.getcwd())#读取当前目录
print result#打印去重后结果

root@kali:~/python/laowangpy/function# 
root@kali:~/python/laowangpy/function# 
root@kali:~/python/laowangpy/function# 
root@kali:~/python/laowangpy/function# python tt.py 
set(['', '.swp', '.pyc', '.png', '.pdf', '.csv', '.jpg', '.py', '.txt', '.xlv'])
root@kali:~/python/laowangpy/function# 
定义一个函数xulie(dirname,info) 参数:dirname:路径名,info:需要序列化的数据,功能:将info数据序列化存储到dirname路径下随机的文件里。  

root@kali:~/python/laowangpy/function# python kt1403pickle.py
root@kali:~/python/laowangpy/function# ls
01funcmaxmin.py      everydir       k301_code.py    kt1402osname.py  xt0302url.py
02funcmaxchar.py     fuc_add.py     k302_arge.py    kt1403pickle.py  xt0303mutilist.py
03gethelpmodule2.py  fuc_name_1.py  k303_arge2.py   testm            xt0501filter.py
03gethelpmodule.py   funvar1.py     k501lambda.py   tt.py
04pathwin.py         funvar2.py     kt1101class.py  V88b8UANwm
05getdirfolder.py    funvar3.py     kt1401time.py   xt0301oushu.py
root@kali:~/python/laowangpy/function# cat V88b8UANwm 
(lp0
I1
aI2
aI3
aI4
aI5
aI6
aI7
a.root@kali:~/python/laowangpy/function# cat kt1403pickle.py 
#!/usr/bin/python
# --*-- coding:utf-8 --*--
import os
import pickle
import random

def xulie(dirname,info):
    if not os.path.exists(dirname):#用于判断变量、文件等是否存在
        return "Not found!!"
    a = pickle.dumps(info)#以字节对象形式返回封装的对象,不需要写入文件中
    filename = ""
    for i in range(10):#random.choice()可以从任何序列,比如list列表中,选取一个随机的元素返回,可以用于字符串、列表、元组等
        filename = filename+random.choice("abcedfghijklmnopqrstuvwxyzABCDEFGHIGKLMNOPQRSTUVWXYZ1234567890")
    filepath = os.path.join(dirname,filename)#将多个路径组合后返回
    f = open(filepath,"a+")
    f.write(a)
    f.close()

a = [1,2,3,4,5,6,7]
xulie("/root/python/laowangpy/function",a)

root@kali:~/python/laowangpy/function# 

root@kali:~/python/laowangpy/function# python kt1403pickle.py 
root@kali:~/python/laowangpy/function# ls
01funcmaxmin.py      cQ3j4uod69     funvar3.py      kt1401time.py    xt0301oushu.py
02funcmaxchar.py     everydir       k301_code.py    kt1402osname.py  xt0302url.py
03gethelpmodule2.py  fuc_add.py     k302_arge.py    kt1403pickle.py  xt0303mutilist.py
03gethelpmodule.py   fuc_name_1.py  k303_arge2.py   testm            xt0501filter.py
04pathwin.py         funvar1.py     k501lambda.py   tt.py
05getdirfolder.py    funvar2.py     kt1101class.py  V88b8UANwm
root@kali:~/python/laowangpy/function# 

运行脚本生成的文件:
cQ3j4uod69
V88b8UANwm
相关标签: python time