时间处理模块

一、时间概念

1.1 时间戳  

  时间戳是指格林威治时间1970年01月01日00时00分00秒(北京时间1970年01月01日08时00分00秒)起至现在的总

    秒数。通俗的讲, 时间戳是一份能够表示一份数据在一个特定时间点已经存在的完整的可验证的数据。

1.2 时区

  为了时间各国的时间能统一,使用了时区的概念。以格林尼治为0时区,总24个时区。 东+,西-

1.3 夏令时

  为了节约夏天的能源,开发出来的一个调节时间。 然后实际证明没什么软用。 中国以前也用过,但是取消掉了。

二、python 代码中的时间

  时间有三种格式:

      时间戳(timestamp)

       时间字符串(Format String)

      结构化的时间(struct_time):(year=2018, month=5, day=1, hour=16, min=37, sec=6)

  python中的时间模块

      time

      datetime

      python-dateutil (pip install)  

2.1 time 模块

  常用方法:

    time.time()   当前的时间戳

    time.sleep()    停止多少时间

2.1.1 时间戳 与 结构化时间 之间相互转换

import time
print(time.localtime())   # 无参数的时候,表示取当前时间
print(time.localtime(0))  # 0时间戳,在中国是 70年8点
print(time.mktime(time.localtime()))

2.1.2 结构化时间 与 格式化字符串时间 相互转换

一、  strftime :  tuple -> 字符串时间

    strftime(format[, tuple]) -> string

     两个参数:

    format:我们定义的格式

    tuple为可选参数,不写的时候,使用当前的时间。

  format的字符:

    %Y  Year with century as a decimal number.
    %m  Month as a decimal number [01,12].
    %d  Day of the month as a decimal number [01,31].
    %H  Hour (24-hour clock) as a decimal number [00,23].
    %M  Minute as a decimal number [00,59].
    %S  Second as a decimal number [00,61].
    %z  Time zone offset from UTC.
    %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.
    %I  Hour (12-hour clock) as a decimal number [01,12].
    %p  Locale's equivalent of either AM or PM.

>>> time.strftime('%Y-%m-%d %X', time.localtime())

'2018-06-24 13:14:35'

二 、 字符串时间  到  结构化时间转换

    strptime(string, format) -> struct_time

    把一个时间的字符串,按照格式进行转化

time.strptime('2018-05-06 22:52:40', "%Y-%m-%d %X")

2.1.3 结构化时间和时间戳 到 固定字符串时间的转换

  字符串时间的格式固定

# 结构化时间 到 固定字符串时间
>>> time.asctime()
'Sun Jun 24 13:40:09 2018'
>>> time.asctime(time.localtime(0))
'Thu Jan  1 08:00:00 1970'

# 时间戳 到 固定字符串时间
>>> time.ctime()
'Sun Jun 24 13:40:39 2018'
>>> time.ctime(0)
'Thu Jan  1 08:00:00 1970'

猜你喜欢

转载自www.cnblogs.com/louhui/p/9220377.html
今日推荐