zoukankan      html  css  js  c++  java
  • time -- make more time

    类型总览

    时间总览

    常遇到的变换过程举例

    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
    

    out

    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
    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
    

    out
    timestamp_get

    一些举例

    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"
    

    out

    数据库utc时间

    datetime
    1、允许为空值,可以自定义值,系统不会自动修改其值。
    2、不可以设定默认值,所以在不允许为空值的情况下,必须手动指定datetime字段的值才可以成功插入数据。
    3、虽然不可以设定默认值,但是可以在指定datetime字段的值的时候使用now()变量来自动插入系统的当前时间。
    结论:datetime类型适合用来记录数据的原始的创建时间,因为无论你怎么更改记录中其他字段的值,datetime字段的值都不会改变,除非你手动更改它。

    timestamp
    1、允许为空值,但是不可以自定义值,所以为空值时没有任何意义。
    2、默认值为CURRENT_TIMESTAMP(),其实也就是当前的系统时间。
    3、数据库会自动修改其值,所以在插入记录时不需要指定timestamp字段的名称和timestamp字段的值,你只需要在设计表的时候添加一个timestamp字段即可,插入后该字段的值会自动变为当前系统时间。
    4、以后任何时间修改表中的记录时,对应记录的timestamp值会自动被更新为当前的系统时间。
    结论:timestamp类型适合用来记录数据的最后修改时间,因为只要你更改了记录中其他字段的值,timestamp字段的值都会被自动更新。

    create_time timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    update_time timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',

    使用时要注意时区,查询结果是datetime类型 datetime.datetime(2019, 9, 27, 15, 57, 38)

    from datetime import datetime
    
    def utc2local( utc_dtm ):
        # UTC 时间转本地时间( +8:00 )
        local_tm = datetime.fromtimestamp( 0 )
        utc_tm = datetime.utcfromtimestamp( 0 )
        offset = local_tm - utc_tm
        return utc_dtm + offset
    
    def local2utc( local_dtm ):
        # 本地时间转 UTC 时间( -8:00 )
        return datetime.utcfromtimestamp( local_dtm.timestamp() )
    
    if __name__ == "__main__":
    
        # utc_tm = datetime.utcnow()
        utc_tm = datetime( 2012, 10, 26, 10, 00, 00 )
    
        print( "src utc time:	", utc_tm.strftime("%Y-%m-%d %H:%M:%S") ) 
    
        # UTC 转本地
        local_tm = utc2local(utc_tm)
        print( "tran loc time:	", local_tm.strftime("%Y-%m-%d %H:%M:%S") ) 
    
        # 本地转 UTC
        utc_tran = local2utc(local_tm)
        print( "tran utc time:	", utc_tran.strftime("%Y-%m-%d %H:%M:%S") )
    
    原文链接:https://blog.csdn.net/u010649766/article/details/79415885
    
  • 相关阅读:
    SpringBoot2.0之一 新建项目helloWorld
    spring boot 的maven设置阿里云仓库
    新建SpringBoot项目运行页面报错Whitelabel Error Page This application has no explicit mapping for /error, so yo
    SpringBoot2.0 最简单的 idea 快速创建项目
    postgresql 按日期范围查询
    postgreSQL 应用case when的例子
    PostgreSQL 数据库NULL值的默认排序行为与查询、索引定义规范
    ASP.NET中在不同的子域中共享Session
    YKCW6-BPFPF-BT8C9-7DCTH-QXGWCYQ7PR-QTHDM-HCBCV-9GKGG-TB2TM
    Asp.net中基于Forms验证的角色验证授权
  • 原文地址:https://www.cnblogs.com/bruspawn/p/10162327.html
Copyright © 2011-2022 走看看