python学习—Day19—import,时间格式转换

python常用内置模块的使用:datetime,logging,os,command


构建模块,以及使用:导入的时候不写后缀(test.py是书写规范,在调用时不需要写)
import demo1.import_text
demo1.import_text.hello()

from demo1 import import_text
import_text.hello()

from demo1.import_text import hello	\\import后面导入的是什么,在调用的时候就必须写什么。这里导入的可以是一个函数,也可以是模块。总结:就是一层一层的调用就可以
hello()

import demo1.import_text as text	\\这里as的用法是给import一个别名
text.hello()
#@File :import_text.py
def hello():
    print('hello world')
hello world
hello world
hello world
hello world

注意文件目录树:模块在单独一个目录中,该目录与程序文件平级



datetime获取时间:

#Subclass relationships:子类间的对应关系
#object
# timedelts
# tzinfo
# time
# date
# datetime
time模块基本不用于取时间,取时间推荐使用datetime模块。

time独有的用法:系统在监控循环中,需要停顿执行,等同linux中的sleep命令。time.sleep也是datetime无法替代的
import time

for i in xrange(1, 5):
    print(i)
    time.sleep(3)
1
2
3
4
\\每隔一秒输出一个。

datetime:定义概念:


操作示例:now获取当前时间,strftime用来表示显示时间的格式
from datetime import datetime
now_time = datetime.now()			\\now就是获取当前时间的方法
print(now_time)
new_time = now_time.strftime('%Y-%m-%d')	\\上图解释4
new_time1 = now_time.strftime('%Y-%m-%d %H:%M:%S')
a = now_time.strftime('%c')		\\%c标准时间格式输出
print(new_time)
print(new_time1)
print(a)
2017-11-09 11:38:17.272000
2017-11-09
2017-11-09 11:38:17
11/09/17 11:38:17


如果获取昨天或前天的时间:



from datetime import datetime, timedelta

now_time = datetime.now()
yesterday = now_time + timedelta(days=-1)
tomorrow = now_time + timedelta(days=+1)
tomorrow = tomorrow.strftime('%Y-%m-%d')
print(yesterday)
print(tomorrow)
2017-11-08 11:50:01.051000
2017-11-10


时间格式的相互转换:时间对象、时间字符串、时间戳

from datetime import datetime
import time

now_time = datetime.now()
print(now_time)
print(type(now_time))
print('##########   time to str   ##########')
# _time = now_time.strftime('%Y-%m-%d %H:%M:%S')	\\实现同样效果的不同方法
_time = datetime.strftime(now_time, '%Y-%m-%d %H:%M:%S')
print(_time)
print(type(_time))
print('##########   str to time   ##########')
_d_time = datetime.strptime(_time, '%Y-%m-%d %H:%M:%S')\\这里格式自己定,可以没有分时秒
print(_d_time)
print(type(_d_time))

print('##########   stamp   ##########')
_a = time.time()					\\使用单下划线,一逼格,二不容易冲突
print(_a)
_m_time = datetime.fromtimestamp(_a)
print(_m_time)
print(type(_m_time))
2017-11-09 12:06:23.670000
<type 'datetime.datetime'>
##########   time to str   ########## \\时间对象转换成字符串格式:使用datetime.strftime()
2017-11-09 12:06:23
<type 'str'>
##########   str to time   ########## \\字符串格式转换成时间对象:使用datetime.strptime()
2017-11-09 12:06:23
<type 'datetime.datetime'>
##########   stamp   ########## \\时间戳格式转换成时间对象:使用datetime.fromtimestamp()
1510200383.67
2017-11-09 12:06:23.670000
<type 'datetime.datetime'>




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值