python之 datetime模块

datetime是python处理时间和日期的标准库.

1.基本对象

from datetime import datetime
datetime.time()   #时,分,秒,微秒 自动转换成str字符串    与 _repr_不一样
datetime.date()    #年,月,日
datetime.datetime()  ##########年,月,日,时,分,秒,微秒    (最常用)

# 例子
t= datetime.time(20,30,1,2)
print('str:',t)    #str: 20:30:01.000002   默认自动转换成str
print('repr',repr(t))   #repr datetime.time(20, 30, 1, 2)

2.实用函数

# 当前日期时间: 
datetime.datetime.now()

# 当前UTC日期时间:
datetime.datetime.utcnow()

# 时间戳转日期时间:
datetime.datetime.fromtimestamp(ts)
# 例子
ts = datetime.datetime.fromtimestamp(1519909295.2198606)    #时间戳转换为日期时间
print(ts)   #2018-03-01 21:01:35.219861

# 日期时间转时间戳
time. mktime(dt. timetuple())

# 时间计算
datetime.timedelta( days=0,seconds=0, microseconds=0 milliseconds=0,minutes=0, hours=0, weeks=0 )


3.时间与字符串之间转换

datetime.strptime(string, format_string)
# 例子 将时间格式的字符串转换为时间对象
day = datetime.datetime.strptime('2018-6-1 13:13:13', '%Y-%m-%d %H:%M:%S')
print(type(day), day)

# 将时间对象进行格式化
now = datetime.datetime.now()     
new_day = now.strftime('%Y-%m-%d %H:%M:%S')   # 注意与time模块的稍有不同
print(type(new_day), new_day)         # <class 'str'> 2018-08-25 22:37:35
print(type(now), now)                # <class 'datetime.datetime'> 2018-08-25 22:37:35.391563

这里写图片描述

4.时区问题:

必须要在时间对象上附加时区信息 !

datetime.timezone( offset, name )

时区对象:

tz_utc = datetime.timezone.utc   #标准时区
print('str:',str(tz_utc))   #str: UTC+00:00
print('repr:',repr(tz_utc))   #repr: datetime.timezone.utc
print('------')

tz_china = datetime.timezone(datetime.timedelta(hours=8),'Asia/Beijing')   #北京(+8区)
print('str:',str(tz_china))   #str: Asia/Beijing
print('repr:',repr(tz_china))   #repr: datetime.timezone(datetime.timedelta(0, 28800), 'Asia/Beijing')
print('------')

tz_america = datetime.timezone(datetime.timedelta(hours=-8),'America/los_Angeles')   #美国时区
print('str:',str(tz_america))   #str: America/los_Angelesg
print('repr:',repr(tz_america))   #repr: datetime.timezone(datetime.timedelta(-1, 57600), 'America/los_Angeles')
print('------')

转换时间:

cn_dt = datetime.datetime(2018,2,27,20,30,tzinfo=tz_china)  #北京时间
print('北京时间:',cn_dt)

utc_dt = cn_dt.astimezone(datetime.timezone.utc)    #0时区
print('零时区时间:str:',str(utc_dt))   #str: 2018-02-27 12:30:00+00:00
print('repr:',repr(utc_dt))  #repr: datetime.datetime(2018, 2, 27, 12, 30, tzinfo=datetime.timezone.utc)
print('------')

us_dt = utc_dt.astimezone(tz_america)           #美国时间
print('美国时间:str:',str(us_dt))   #str: 2018-02-27 04:30:00-08:00
print('repr:',repr(us_dt))  #repr: datetime.datetime(2018, 2, 27, 4, 30, tzinfo=datetime.timezone(datetime.timedelta(-1, 57600), 'America/los_Angeles'))
print('------')
posted @ 2018-08-25 22:53  此时相望不相闻  阅读(96)  评论(0编辑  收藏  举报