python导入时间模块_Python的模块和时间模块的使用

本文介绍了Python中的模块和时间模块的使用。讲解了如何导入模块,包括import和from...import的不同方式,并详细阐述了datetime模块获取和操作时间的方法,如获取当前时间、昨天和明天的时间,以及时间格式的相互转换。同时,展示了时间戳与时间对象的转换过程。
摘要由CSDN通过智能技术生成

1、  Python的模块

为了编写可维护的代码,我们把很多函数分组,分别放到不同的文件里,这样,每个文件包含的代码就相对较少,很多编程语言都采用这种组织代码的方式。在Python中,一个.py文件就称之为一个模块(Module)。

为了避免模块名冲突,Python又引入了按目录来组织模块的方法,称为包(Package)。

每个包下面都有一个__init__.py文件,这个文件是必须存在的,否则,Python就把这个目录当成普通目录,而不是一个包。__init__.py可以是空文件,也可以有Python代码,因为__init__.py本身就是一个模块,

2、  Python的模块导入

Import,导入模块使用

import module1[, module2[,... moduleN]

from modname import name1[, name2[, ... nameN]]

Python的模块导入方法:

a.  import testmodule.test

testmodule.test.hello()

b.  from testmodule import test

test.hello()

c.  from testmodule.test import hello

hello()

d.  import testmodule.test as abc #别名

abc.hello()

3、  Datetime获取时间

子类之间的对应关系

Subclass relationships:

object

timedelta

tzinfo

time

date

datetime

time

python中时间日期常用的参数:

%Y 带世纪部分的十制年份

%m 十进制表示的月份

%d 十进制表示的每月的第几天

%H 24小时制的小时

%M 十时制表示的分钟数

%S 十进制的秒数

%c  标准时间,如:04/25/17 14:35:14  类似于这种形式

取时间建议使用datetime

Time独有的用法:

import time

for i in xrange(1, 10):

print(i)

time.sleep(1)

datetime:

#now用来获取当前时间,strftime用来显示时间的格式

from datetime import datetime

now_time = datetime.now()

print(now_time)

new_time = now_time.strftime('%Y-%m-%d %H:%M:%S')

a = now_time.strftime('%c')

print(new_time)

print(a)

结果:

2017-11-09 23:53:23.207000

2017-11-09 23:53:23

11/09/17 23:53:23

获取昨天或者明天的时间:

from datetime import datetime, timedelta

now_time = datetime.now()

yesterday = now_time + timedelta(days=-1) #昨天的时间

tomorrow = now_time + timedelta(days=1) #明天的时间

tomorrow1 = tomorrow.strftime('%Y-%m-%m')

print(yesterday)

print(tomorrow)

print(tomorrow1)

结果:

2017-11-09 00:14:59.750000

2017-11-11 00:14:59.750000

2017-11-11

4、  时间格式的相互转换

每个时间戳都以自从1970年1月1日午夜(历元)经过了多长时间来表示

#时间对象和字符串的互相转换

from datetime import datetime

now_time = datetime.now()

print(now_time)

print(type(now_time))

# _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))

_d_time = datetime.strptime(_time, '%Y-%m-%d %H:%M:%S') #将字符串转换成时间对象

print(_d_time)

print(type(_d_time))

结果:

2017-11-10 00:27:10.098000

2017-11-10 00:27:10

2017-11-10 00:27:10

#时间戳转换为事件对象

from datetime import datetime

import time

_a = time.time()

print(_a)

_a_time = datetime.fromtimestamp(_a)

print(_a_time)

print(type(_a_time))

结果:

1510245208.6

2017-11-10 00:33:28.600000

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值