博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Python 字符串时间转换time或者datetime时间戳
阅读量:2051 次
发布时间:2019-04-28

本文共 3196 字,大约阅读时间需要 10 分钟。

#时间字符串 --> 时间戳

  • time 模块
timestring='2018-06-26 10:14:49'# 字符串时间转为时间戳def Changetime(str1):    Unixtime = int(time.mktime(time.strptime(str1, '%Y-%m-%d %H:%M:%S'))*1000)    return Unixtimet1 = time.strptime(str1, '%Y-%m-%d %H:%M:%S') #将字符串转存成时间元组t2 = Changetime(timestring)  #1529979289000
  • time.mktime() 与 time.localtime() 互为还原函数。

  • time.mktime(timetuple) :将时间元组转换成时间戳

  • time.localtime([timestamp]):将时间戳转会为时间元组

    注意:datetime 模块没有能获取时间戳的函数

#时间戳 --> 时间字符串

  • time模块
timestamp = time.time()  #1530098655.6190026timestruct = time.localtime(timestamp)t3 = time.strftime('%Y-%m-%d %H:%M:%S', timestruct) #'2018-06-27 19:24:15'
  • datetime 模块
import datetimetimestamp = 1530098655.6190026datetime_struct = datetime.datetime.fromtimestamp(timestamp)t4 = datetime_struct.strftime('%Y-%m-%d %H:%M:%S')  #'2018-06-27 19:24:15'datetime_struct = datetime.datetime.utcfromtimestamp(timestamp) t5 = datetime_struct.strftime('%Y-%m-%d %H:%M:%S')  #'2018-06-27 11:24:15'
  • fromtimestamp(timestamp[, tz]):将时间戳转为当地的时间元组
  • utcfromtimestamp(timestamp):将时间戳转为UTC的时间元组。以北京为例:utc时间比北京当地时间少8个小时。
    ###注意:time 和 datetime 之间可以用时间戳来相互转换。
    #时间差计算
  • datetime
#几天/周前import datetimeimport timenow = datetime.datetime.now()three_days_ago = now + datetime.timedelta(days=-3)three_weeks_ago = now + datetime.timedelta(weeks=-3)#几天/周后three_days_later = now + datetime.timedelta(days=3)three_weeks_later = now + datetime.timedelta(weeks=3)#获取时间差start = datetime.datetime.now()time.sleep(30)end = datetime.datetime.now()print (end-start).days # 0 天数print (end-start).total_seconds() # 30.029522 精确秒数print (end-start).seconds # 30 秒数print (end-start).microseconds # 29522 毫秒数

注意:没有months和years

注意:获取的时间差没有分钟

#任意时间字符串转换时间对象

dateutil 与日期相关库里的一个日期解析器 能够将字符串 转换为日期格式

import timefrom dateutil import parsertime_string = time.ctime() # 'Wed Jun 27 19:40:17 2018' 可以是任意的时间格式 
datetime_struct = parser.parse(time_string)print type(datetime_struct) #
print datetime_struct.strftime('%Y-%m-%d %H:%M:%S') # 2018-06-27 19:40:17

天级别分段

def split_date_ranges(start_date,end_date,time_interval):    data_ranges = []    d1 = datetime.datetime.strptime(start_date, '%Y-%m-%d')    d2 = datetime.datetime.strptime(end_date, '%Y-%m-%d')    print((d2 - d1).days)    count_day= (d2 - d1).days +1    if count_day // time_interval ==0:        data_ranges.append([start_date,end_date])    else:        for item in range(1,math.ceil(count_day/time_interval)+1):            s_date = datetime.datetime.strptime(str(start_date), '%Y-%m-%d').date()            f_date = datetime.datetime.strptime(str(s_date), '%Y-%m-%d').date() + datetime.timedelta(time_interval-1)            start_date = datetime.datetime.strptime(str(f_date), '%Y-%m-%d').date() + datetime.timedelta(1)            if ((datetime.datetime.strptime(str(f_date), '%Y-%m-%d')  - d2).days > 0 ) and ((datetime.datetime.strptime(str(s_date), '%Y-%m-%d')  - d2).days > 0 ):                continue            elif ((datetime.datetime.strptime(str(f_date), '%Y-%m-%d')  - d2).days > 0 ) and ((datetime.datetime.strptime(str(s_date), '%Y-%m-%d')  - d2).days <= 0 ) :                f_date = end_date            data_ranges.append([str(s_date), str(f_date)])    print(data_ranges)    return data_ranges

在这里插入图片描述

#参考文献

转载地址:http://dewlf.baihongyu.com/

你可能感兴趣的文章
Leetcode C++《热题 Hot 100-16》448.找到所有数组中消失的数字
查看>>
Leetcode C++《热题 Hot 100-17》461.汉明距离
查看>>
Leetcode C++《热题 Hot 100-18》538.把二叉搜索树转换为累加树
查看>>
Leetcode C++《热题 Hot 100-19》543.二叉树的直径
查看>>
Leetcode C++《热题 Hot 100-21》581.最短无序连续子数组
查看>>
Leetcode C++《热题 Hot 100-22》2.两数相加
查看>>
Leetcode C++《热题 Hot 100-23》3.无重复字符的最长子串
查看>>
Leetcode C++《热题 Hot 100-24》5.最长回文子串
查看>>
Leetcode C++《热题 Hot 100-26》15.三数之和
查看>>
Leetcode C++《热题 Hot 100-27》17.电话号码的字母组合
查看>>
Leetcode C++《热题 Hot 100-28》19.删除链表的倒数第N个节点
查看>>
Leetcode C++《热题 Hot 100-29》22.括号生成
查看>>
Leetcode C++《热题 Hot 100-30》31.下一个排列
查看>>
Leetcode C++《热题 Hot 100-40》64.最小路径和
查看>>
Leetcode C++《热题 Hot 100-41》75.颜色分类
查看>>
Leetcode C++《热题 Hot 100-42》78.子集
查看>>
Leetcode C++《热题 Hot 100-43》94.二叉树的中序遍历
查看>>
Leetcode C++ 《第175场周赛-1 》5332.检查整数及其两倍数是否存在
查看>>
Leetcode C++ 《第175场周赛-2 》5333.制造字母异位词的最小步骤数
查看>>
Leetcode C++ 《第175场周赛-3》1348. 推文计数
查看>>