首页 > 其他 > 详细

time -- make more time

时间:2018-12-22 21:33:02      阅读:190      评论:0      收藏:0      [点我收藏+]

技术分享图片

类型总览

技术分享图片

常遇到的变换过程举例

1. timestamp to datetime then time_str ("20181222" , "2018-12-22")

def time_stamp_to_str(timeStamp):
    import datetime
    datetime_obj = datetime.datetime.utcfromtimestamp(timeStamp) # timestamp to datetime
    print(datetime_obj)
    time_year_second = datetime_obj.strftime("%Y-%m-%d %H:%M:%S")  # datetime to str 
    time_year_day = datetime_obj.strftime("%Y%m%d")
    print("time_year_second", time_year_second)
    print("time_year_day", time_year_day)
    return time_year_day, time_year_second
time_stamp_to_str(1545470518)  # 秒为单位, 若是ms OSError: [Errno 22] Invalid argument
# [out]
2018-12-22 09:21:58
time_year_second 2018-12-22 09:21:58
time_year_day 20181222

2. time_str to datetime then timestamp

def time_str_date(date_str):
    """
    date_str ‘20000215‘ -> 2000
    :param date_str:
    :return: year
    """
    import datetime
    try:
        date_time = datetime.datetime.strptime(date_str, ‘%Y%m%d‘)
        return date_time.year
    except Exception as _:
        return ‘‘

3. time_str to time_tuple then time_stamp

import time
time_str = ‘2018-12-22 17:21:58‘
time_tuple = time.strptime(time_str, "%Y-%m-%d %H:%M:%S")
print(time_tuple)
time_stamp = time.mktime(time_tuple)
print("time_stamp ==== ",time_stamp)

技术分享图片

4. time_stamp to time_tuple then str

import time
t = 1545470518
tarray = time.localtime(t)
print(tarray)
time_str = time.strftime("%Y-%m-%d %H:%M:%S", tarray)
time_str

技术分享图片

datetime 类型可以直接做比较,其方法有:dir(datetime_obj) 或 help(datetime_obj) , 创建datetime_obj快速方法
datetime.now()

好用的时间模块

arrow, maya 都号称是 datetime for humanize, 操作简单,看一下文档就会,真的很棒~
https://arrow.readthedocs.io/en/latest/

pip install arrow
技术分享图片

拿到的数据是 time_str

arrow.get(‘2013-05-05 12:30:45‘, ‘YYYY-MM-DD HH:mm:ss‘)
arrow.get(2012,12,12)
arrow.get("2013-02-23", "YYYY-MM-DD")
arrow.get("20130223", "YYYYMMDD")
arrow.get("20130223", "YYYYMMDD").year
arrow.get("20130223", "YYYYMMDD").timestamp

技术分享图片
技术分享图片

一些举例

import arrow
local = arrow.utcnow().to(‘US/Pacific‘)

local.format()
# Out[10]: u‘2018-12-02 21:21:37-08:00‘

print(arrow.now())

print(arrow.utcnow().to("Asia/Shanghai"))  # 不能打错一个字母,不能有空格
print(arrow.utcnow().to("Asia/Hong_Kong"))
print(arrow.utcnow().to("Asia/Tokyo"))  
print(arrow.utcnow().to("Asia/Seoul"))

lo = local.shift(hours=-2)
lo

arrow.get(‘2018-12-22T01:30:24.380226-08:00‘)
local.timestamp
local.format()
local.format("YYYY-MM-DD HH:mm:ss ZZ")

local.humanize()
local.humanize(locale="zh")  # "ko_kr"

技术分享图片

time -- make more time

原文:https://www.cnblogs.com/bruspawn/p/10162327.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!