模块_datetime包_datetime模块

 

from datetime import datetime


# 创建datetime类型的数据
a = datetime(2019, 5, 1, 12, 12)
print(a)

b = datetime.now()  # 获取当前本地时间
print(b)

c = datetime.utcnow()  # 获取当前世界时间
print(c)



# datetime类型 ->字符串类型
d = datetime(2019, 10, 1, 8, 30, 25)
print(d.strftime("%Y-%m-%d %H:%M:%S"))  # 字符串类型 2019-10-01 08:30:25
e = datetime(2017, 9, 28, 10, 3, 43)
print(e.strftime('%Y%m%d-%A,%H %M %S'))  # 20170928-Thursday,10 03 43
f = datetime(2017, 9, 30, 10, 3, 43)
print(f.strftime('%A,%B %d,%Y'))  # Saturday,September 30,2017

# 字符串类型->datetime类型
str1 = '2017年9月30日星期六8时42分24秒'
struct_time = datetime.strptime(str1, "%Y年%m月%d日星期六%H时%M分24秒")
print(struct_time)  # datetime类型
print(type(struct_time))  # datetime类型


m = datetime.now()
# UnicodeEncodeError: 'locale' codec can't encode character '\u4eca' in position 0: encoding error
# 原因是"%Y年%m月%d日 %H时%M分%S秒"中包含了中文,中文没有转化为unicode编码失败
# print(m.strftime('今天是%Y年%m月%d日'))
temp = m.strftime('今天是%Y年%m月%d日'.encode('unicode_escape').decode('utf8'))
print(temp.encode('utf-8').decode('unicode_escape'))

http://www.caotama.com/20249.html

 

posted @ 2020-05-07 23:59  CherryYang  阅读(419)  评论(0)    收藏  举报