前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >2-datetime 模块

2-datetime 模块

作者头像
py3study
发布2020-01-02 16:27:04
9610
发布2020-01-02 16:27:04
举报
文章被收录于专栏:python3python3

datetime

时间转字符串

在我们的使用中,我们常常需要将时间转换为字符串,用来作为文件的名字或者用于加密字符的输出等等。例子:

代码语言:javascript
复制
from datetime import datetime 
datetime.strftime(datetime.now(),"%Y-%m-%d %H:%M:%S")

记忆方式也很简单,str from time

字符转时间

有时候我们需要将一个字符给转换为时间对象

代码语言:javascript
复制
from datetime import datetime 
>>> datetime.strptime('2018-09-09',"%Y-%m-%d")
datetime.datetime(2018, 9, 9, 0, 0)

时间戳的转换

代码语言:javascript
复制
import time 
from datetime import datetime 
stamp = time.time()
datetime.fromtimestamp(stamp)

timedelta

代码语言:javascript
复制
import datetime
print('microseconds:', datetime.timedelta(microseconds=1))
print('milliseconds:', datetime.timedelta(milliseconds=1))
print('seconds :', datetime.timedelta(seconds=1))
print('minutes :', datetime.timedelta(minutes=1))
print('hours :', datetime.timedelta(hours=1))
print('days :', datetime.timedelta(days=1))
print('weeks :', datetime.timedelta(weeks=1))

加 就是 延后几秒; 减 就是提前几秒

转换格式

Symbol

Meaning

Example

%a

Abbreviated weekday name

'Wed'

%A

Full weekday name

'Wednesday'

%w

Weekday number: 0 (Sunday) through 6 (Saturday)

'3'

%d

Day of the month (zero padded)

'13'

%b

Abbreviated month name

'Jan'

%B

Full month name

'January'

%m

Month of the year

'01'

%y

Year without century

'18'

%Y

Year with century

'2018'

%H

Hour from 24-hour clock

'17'

%I

Hour from 12-hour clock

'05'

%p

AM/PM

'PM'

%M

Minutes

'00'

%S

Seconds

'00'

%f

Microseconds

'000000'

%z

UTC offset for time zone–aware objects

'-0500'

%Z

Time zone name

'EST'

%j

Day of the year

'013'

%W

Week of the year

'02'

%c

Date and time representation for the current locale

'Wed Jan 13 17:00:00 2016'

%x

Date representation for the current locale

'01/13/16'

%X

Time representation for the current locale

'17:00:00'

%%

A literal % character

'%'

tips

工作中经常需要用到美国时间,做一个记录。 utc晚了8个小时,所以要减去即是美国时间

代码语言:javascript
复制
datetime.strftime(datetime.utcnow()-timedelta(hours=8),'%Y-%m-%d %H:%M:%S')

参考

《The Python3 Standard Library By Example》

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-10-11 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • datetime
    • 时间转字符串
      • 字符转时间
        • 时间戳的转换
          • timedelta
            • 转换格式
              • tips
              • 参考
              领券
              问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档