Python 时间转换

一、13位时间戳转为正常格式时间

# encoding: utf-8

import time
import datetime

# 获得当前时间时间戳,10位
now = int(time.time())
print(now)

#转换为其他日期格式,如:"%Y-%m-%d %H:%M:%S"
timeArray = time.localtime(now)
print(timeArray)
otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
print(otherStyleTime)

# 13位时间戳转正常格式时间 "%Y-%m-%d %H:%M:%S"
stamp = 1588032000000
datatime_13 = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(float(str(stamp)[0:10])))
#datatime = datatime+'.'+str(stamp)[10:]
print(datatime_13)

print("===从pd.frame()获取的字段默认带索引,这里需要去除===")
str = '16  1585440001000'
print(str[-13:-3])

打印:

1589179795
time.struct_time(tm_year=2020, tm_mon=5, tm_mday=11, tm_hour=6, tm_min=49, tm_sec=55, tm_wday=0, tm_yday=132, tm_isdst=0)
2020-05-11 06:49:55
2020-04-28 00:00:00
===从pd.frame()获取的字段默认带索引,这里需要去除===
1585440001

13位是毫秒时间戳,10位是秒时间戳。

转换思路

13位转为10位,可以直接除以1000或者字符串只截取前10位即可。

mport time

# 输入毫秒级的时间,转出正常格式的时间
def timeStamp(timeNum):
    timeStamp = float(timeNum/1000)
    timeArray = time.localtime(timeStamp)
    otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
    print otherStyleTime

或者可以参考已经封装好的方法:

import datetime
import time

def get_float_time_stamp():
    datetime_now = datetime.datetime.now()
    return datetime_now.timestamp()

def get_time_stamp16():
    # 生成16时间戳   eg:1540281250399895    -ln
    datetime_now = datetime.datetime.now()
    print(datetime_now)

    # 10位,时间点相当于从UNIX TIME的纪元时间开始的当年时间编号
    date_stamp = str(int(time.mktime(datetime_now.timetuple())))

    # 6位,微秒
    data_microsecond = str("%06d"%datetime_now.microsecond)

    date_stamp = date_stamp+data_microsecond
    return int(date_stamp)

def get_time_stamp13():
    # 生成13时间戳   eg:1540281250399895
    datetime_now = datetime.datetime.now()

    # 10位,时间点相当于从UNIX TIME的纪元时间开始的当年时间编号
    date_stamp = str(int(time.mktime(datetime_now.timetuple())))

    # 3位,微秒
    data_microsecond = str("%06d"%datetime_now.microsecond)[0:3]

    date_stamp = date_stamp+data_microsecond
    return int(date_stamp)

def stampToTime(stamp):
    datatime = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(float(str(stamp)[0:10])))
    datatime = datatime+'.'+str(stamp)[10:]
    return datatime

if __name__ == '__main__':
    a1 = get_time_stamp16()
    print(a1)
    print(stampToTime(a1))
    a2 = get_time_stamp13()
    print(a2)
    print(stampToTime(a2))

线上测试工具:https://tool.lu/coderunner/

二、实战

# -*- coding:utf-8 -*-

"""
@author: Corwien
@file: crypto.py
@time: 20/5/9 14:10
"""
import time
import datetime
import pandas as pd
import ccxt

# 初始化交易所
binance_exchange = ccxt.binance({
    'apiKey': 'wNG6XatvBxxxxs235656',
    'secret': '8gU3JCAFxxxxxer457s',
    'timeout': 15000,
    'enableRateLimit': True,
})

symbol = "BTC/USDT"

# 交易所数据结构
print('交易所id:', binance_exchange.id)
print('交易所名称:', binance_exchange.name)
print('是否支持共有API:', binance_exchange.has['publicAPI'])
print('是否支持私有API:', binance_exchange.has['privateAPI'])
print('支持的时间频率:', binance_exchange.timeframes)
print('最长等待时间(s):', binance_exchange.timeout / 1000)
print('访问频率(s):', binance_exchange.rateLimit / 1000)

# fetch_ohlcv(self, symbol, timeframe='1m', since=None, limit=None, params={})

# 先获得时间数组格式的日期(获取60天之内的数据)
threeDayAgo = (datetime.datetime.now() - datetime.timedelta(days = 60 ))
print(datetime.datetime.now())
# 转换为时间戳
timeStamp = int(time.mktime(threeDayAgo.timetuple())) * 1000

# 转换为其他字符串格式
# otherStyleTime = threeDayAgo.strftime("%Y-%m-%d %H:%M:%S")
limit = 1000

# K线数据数据获取
if binance_exchange.has['fetchOHLCV']:
    kline_data = pd.DataFrame(binance_exchange.fetch_ohlcv(symbol, timeframe='1d', since=timeStamp, limit=limit))
    kline_data.columns = ['Datetime', 'Open', 'High', 'Low', 'Close', 'Vol']
    #kline_data['Datetime'] = kline_data['Datetime'].apply(binance_exchange.iso8601)
    # kline_data['Datetime'] = pd.to_datetime(kline_data['Datetime'], unit='ms') #utc shijian
    #kline_data['Datetime'] = pd.to_datetime(kline_data['Datetime'], unit='ns') #utc
    print(kline_data['Datetime'])
    #kline_data.set_index('Datetime', inplace=True)
    #print(kline_data['Datetime'])
    # kline_data['Datetime'] = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(float(str(kline_data['Datetime'])[0:10])))

res = kline_data.head(100)
#print(type(res))
kline_data.info()
print(res)

打印:

交易所id: binance
交易所名称: Binance
是否支持共有API: True
是否支持私有API: True
支持的时间频率: {'1m': '1m', '3m': '3m', '5m': '5m', '15m': '15m', '30m': '30m', '1h': '1h', '2h': '2h', '4h': '4h', '6h': '6h', '8h': '8h', '12h': '12h', '1d': '1d', '3d': '3d', '1w': '1w', '1M': '1M'}
最长等待时间(s): 15.0
访问频率(s): 0.5
2020-05-11 14:19:55.658095
0     1584057600000
1     1584144000000
2     1584230400000
3     1584316800000
4     1584403200000
5     1584489600000
6     1584576000000
7     1584662400000
8     1584748800000
9     1584835200000
10    1584921600000
...
50    1588377600000
51    1588464000000
52    1588550400000
53    1588636800000
54    1588723200000
55    1588809600000
56    1588896000000
57    1588982400000
58    1589068800000
59    1589155200000
Name: Datetime, dtype: int64
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 60 entries, 0 to 59
Data columns (total 6 columns):
 #   Column    Non-Null Count  Dtype  
---  ------    --------------  -----  
 0   Datetime  60 non-null     int64  
 1   Open      60 non-null     float64
 2   High      60 non-null     float64
 3   Low       60 non-null     float64
 4   Close     60 non-null     float64
 5   Vol       60 non-null     float64
dtypes: float64(5), int64(1)
memory usage: 2.9 KB
         Datetime     Open      High      Low    Close            Vol
0   1584057600000  4800.01   5955.00  3782.13  5578.60  402201.673764
1   1584144000000  5576.05   5640.52  5055.13  5172.06  136910.135974
2   1584230400000  5172.48   5940.00  5093.10  5361.30  139916.146534
3   1584316800000  5360.33   5365.42  4442.12  5028.97  227276.922760
4   1584403200000  5028.86   5525.00  4921.45  5312.64  150089.926318
5   1584489600000  5312.64   5436.17  5009.37  5393.04  137127.634894
6   1584576000000  5393.26   6400.00  5252.53  6162.37  199020.873439
7   1584662400000  6162.05   6900.00  5670.00  6208.36  219298.329514
8   1584748800000  6204.57   6456.98  5860.02  6186.98  128913.668363
9   1584835200000  6187.04   6407.87  5734.01  5816.19  119115.990527
10  1584921600000  5816.05   6600.00  5688.00  6467.31  164674.215785
...
57  1588982400000  9800.02   9914.25  9520.00  9539.40   81950.679567
58  1589068800000  9539.10   9574.83  8117.00  8722.77  183865.182028
59  1589155200000  8722.77   8805.14  8613.01  8710.66   16405.257102

优化:
我们可以从上边的打印看出,kline_data['Datetime'] 获取到的数据带索引 1 1584144000000,而不是单独的一个时间戳字段1584144000000, 所以,这里我们需要对这个进行掐头去尾处理str(kline_data['Datetime'])[-13:-3]

 # kline_data['Datetime'] = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(float(str(kline_data['Datetime'])[0:10])))

 # 新的
kline_data['Datetime'] = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(float(str(kline_data['Datetime'])[-13:-3])))

错误总结

上边犯了一个大错误,就是使用单个的方法处理dataframe结构的数据,所以,造成报错,对于pandas数据结构,我们应该使用pandas带的方法来处理。

# -*- coding:utf-8 -*-

"""
@author: Corwien
@file: crypto.py
@time: 20/5/9 14:10
"""
import time
import datetime
import pandas as pd
import ccxt

# 初始化交易所
binance_exchange = ccxt.binance({
    'apiKey': 'wNG6XatvBxxxxs235656',
    'secret': '8gU3JCAFxxxxxer457s',
    'timeout': 15000,
    'enableRateLimit': True,
})

symbol = "BTC/USDT"

# 交易所数据结构
print('交易所id:', binance_exchange.id)
print('交易所名称:', binance_exchange.name)
print('是否支持共有API:', binance_exchange.has['publicAPI'])
print('是否支持私有API:', binance_exchange.has['privateAPI'])
print('支持的时间频率:', binance_exchange.timeframes)
print('最长等待时间(s):', binance_exchange.timeout / 1000)
print('访问频率(s):', binance_exchange.rateLimit / 1000)

# fetch_ohlcv(self, symbol, timeframe='1m', since=None, limit=None, params={})

# 先获得时间数组格式的日期(获取60天之内的数据)
threeDayAgo = (datetime.datetime.now() - datetime.timedelta(days = 60 ))
print(datetime.datetime.now())
# 转换为时间戳
timeStamp = int(time.mktime(threeDayAgo.timetuple())) * 1000

# 转换为其他字符串格式
# otherStyleTime = threeDayAgo.strftime("%Y-%m-%d %H:%M:%S")
limit = 1000

# pd.to_datetime()
# https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_datetime.html#pandas-to-datetime

# K线数据数据获取
if binance_exchange.has['fetchOHLCV']:
    tickers = binance_exchange.fetch_ohlcv(symbol, timeframe='1d', since=timeStamp, limit=limit)
    print(tickers)

    kline_data = pd.DataFrame(tickers)
    kline_data.columns = ['Datetime', 'Open', 'High', 'Low', 'Close', 'Vol']
    # kline_data['Datetime'] = kline_data['Datetime'].apply(binance_exchange.iso8601)  # iso8601 2019-12-07T15:27:33.630Z
     kline_data['Datetime'] = pd.to_datetime(kline_data['Datetime'], unit='ms') #输出: 2019-12-07
    # kline_data['Datetime']= pd.to_datetime(kline_data['Datetime'].values, utc=True, unit='ms')  # 输出:2020-05-03 00:00:00+00:00

res = kline_data.head(100)
print(res)

打印:

交易所id: binance
交易所名称: Binance
是否支持共有API: True
是否支持私有API: True
支持的时间频率: {'1m': '1m', '3m': '3m', '5m': '5m', '15m': '15m', '30m': '30m', '1h': '1h', '2h': '2h', '4h': '4h', '6h': '6h', '8h': '8h', '12h': '12h', '1d': '1d', '3d': '3d', '1w': '1w', '1M': '1M'}
最长等待时间(s): 15.0
访问频率(s): 0.5
2020-05-11 16:15:26.711992
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 60 entries, 0 to 59
Data columns (total 6 columns):
 #   Column    Non-Null Count  Dtype         
---  ------    --------------  -----         
 0   Datetime  60 non-null     datetime64[ns]
 1   Open      60 non-null     float64       
 2   High      60 non-null     float64       
 3   Low       60 non-null     float64       
 4   Close     60 non-null     float64       
 5   Vol       60 non-null     float64       
dtypes: datetime64[ns](1), float64(5)
memory usage: 2.9 KB
     Datetime     Open      High      Low    Close            Vol
0  2020-03-13  4800.01   5955.00  3782.13  5578.60  402201.673764
1  2020-03-14  5576.05   5640.52  5055.13  5172.06  136910.135974
2  2020-03-15  5172.48   5940.00  5093.10  5361.30  139916.146534
3  2020-03-16  5360.33   5365.42  4442.12  5028.97  227276.922760
4  2020-03-17  5028.86   5525.00  4921.45  5312.64  150089.926318
5  2020-03-18  5312.64   5436.17  5009.37  5393.04  137127.634894
6  2020-03-19  5393.26   6400.00  5252.53  6162.37  199020.873439
7  2020-03-20  6162.05   6900.00  5670.00  6208.36  219298.329514
8  2020-03-21  6204.57   6456.98  5860.02  6186.98  128913.668363
9  2020-03-22  6187.04   6407.87  5734.01  5816.19  119115.990527
10 2020-03-23  5816.05   6600.00  5688.00  6467.31  164674.215785
11 2020-03-24  6465.25   6833.00  6371.33  6744.72  151138.009878
12 2020-03-25  6744.69   6957.96  6450.00  6677.43  132155.734989
13 2020-03-26  6677.42   6780.00  6510.00  6737.36   83026.555211
14 2020-03-27  6737.27   6842.59  6261.00  6359.11   82914.968354
15 2020-03-28  6359.11   6360.00  6024.00  6236.65   93159.693429
16 2020-03-29  6236.65   6266.00  5866.56  5881.42   63311.627714
17 2020-03-30  5880.50   6599.00  5857.76  6394.38  118889.549992
18 2020-03-31  6394.45   6523.23  6321.40  6410.44   72337.595259
19 2020-04-01  6412.14   6679.94  6150.11  6642.92   97500.752400
20 2020-04-02  6643.36   7198.00  6551.00  6794.09  149299.906871
21 2020-04-03  6793.86   7048.00  6602.10  6734.10  104080.276939
22 2020-04-04  6732.97   6990.41  6650.01  6856.99   72990.861139
23 2020-04-05  6857.41   6895.54  6677.52  6772.78   49685.356983
24 2020-04-06  6772.78   7355.14  6765.00  7329.90  118052.000832
25 2020-04-07  7329.90   7459.69  7077.00  7197.32  103585.168918
26 2020-04-08  7197.32   7420.00  7150.00  7361.28   76059.145838
27 2020-04-09  7360.26   7371.92  7108.08  7283.54   61094.872417
28 2020-04-10  7283.54   7295.75  6739.98  6858.92  104674.623375
29 2020-04-11  6858.92   6944.30  6760.00  6876.83   45470.293206
30 2020-04-12  6876.84   7177.00  6780.00  6903.79   73868.666501
31 2020-04-13  6903.79   6903.79  6575.00  6837.91   96415.476573
32 2020-04-14  6838.04   6978.00  6754.28  6868.70   69068.623285
33 2020-04-15  6868.57   6933.00  6605.00  6621.24   61571.384994
34 2020-04-16  6621.25   7190.00  6468.27  7101.94  125009.857539
35 2020-04-17  7101.99   7148.12  6972.98  7027.55   54126.509763
36 2020-04-18  7026.78   7293.08  7014.40  7248.60   49488.542819
37 2020-04-19  7248.60   7266.15  7055.60  7120.74   45664.863930
38 2020-04-20  7121.40   7220.00  6751.00  6826.83   90149.491370
39 2020-04-21  6828.98   6940.00  6762.00  6841.37   60109.710808
40 2020-04-22  6841.36   7156.38  6818.00  7125.14   61486.377334
41 2020-04-23  7125.12   7738.00  7020.00  7482.39  102773.569561
42 2020-04-24  7483.96   7615.96  7388.00  7505.00   60182.119939
43 2020-04-25  7505.00   7705.00  7431.07  7538.67   43874.427726
44 2020-04-26  7539.03   7700.00  7480.00  7693.10   50522.616209
45 2020-04-27  7693.10   7792.02  7606.00  7774.62   65441.339576
46 2020-04-28  7773.51   7780.00  7659.12  7738.98   46302.752638
47 2020-04-29  7738.58   8952.89  7710.05  8778.57  183546.887514
48 2020-04-30  8778.58   9460.00  8401.00  8620.00  206277.214124
49 2020-05-01  8620.00   9059.18  8613.56  8826.96   91468.815059
50 2020-05-02  8825.67   9010.00  8753.00  8972.05   59002.087550
51 2020-05-03  8972.58   9200.00  8712.00  8894.16   90126.065643
52 2020-05-04  8894.15   8950.00  8522.00  8871.96   84418.512331
53 2020-05-05  8871.92   9118.58  8760.00  9021.83   76480.765342
54 2020-05-06  9021.36   9395.00  8906.21  9142.92  105925.302420
55 2020-05-07  9143.40  10067.00  9021.00  9986.40  147154.611378
56 2020-05-08  9986.30  10035.96  9705.00  9800.01  100683.796400
57 2020-05-09  9800.02   9914.25  9520.00  9539.40   81950.679567
58 2020-05-10  9539.10   9574.83  8117.00  8722.77  183865.182028
59 2020-05-11  8722.77   8805.14  8583.89  8625.27   22324.248009

三、datetime标准时间库

获取当前时间

import datetime

day = datetime.datetime.now()
day2 = datetime.date.today()
print("当前年月日时分秒:", day)
print("只查看年月日:", day2)

# time 模块
create_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
print("当前时间,没有微秒:", create_time)

执行结果:
当前年月日时分秒(含有微秒): 2018-09-19 21:18:57.132640
只查看年月日: 2018-09-19
当前时间,没有微秒: 2018-09-19 21:18:57

只查看时分秒

"""
作者:Wei
日期:2018/9/15 17:20
Python版本:3.7
"""
import datetime

def CutHour(time=datetime.datetime.now()):
    """截取时分秒"""
    new_time = str(time)
    hour = new_time[11:19]
    return "".join(hour)

print(CutHour())

执行结果:
21:33:25

timestamp转换为datetime

import datetime

t = 1537000000.0
print(datetime.datetime.fromtimestamp(t))

执行结果:
2018-09-15 16:26:40

str转换为datetime

很多时候,用户输入的日期和时间是字符串,要处理日期和时间,首先必须把str转换为datetime。转换方法是通过datetime.strptime()实现,需要一个日期和时间的格式化字符串:

import datetime

cday = datetime.datetime.strptime('2018-9-19 18:19:59', '%Y-%m-%d %H:%M:%S')
print(cday)

执行结果:
    2018-09-19 18:19:59

datetime转换为str
import datetime

now = datetime.datetime.now()
print(now.strftime('%a, %b %d %H:%M'))

执行结果:
Wed, Sep 19 21:29


参考文章:
Python3日期与时间戳转换的几种方法详解
python生成13位或16位时间戳以及反向解析时间戳
python官方文档之datetime --- 基本的日期和时间类型

为者常成,行者常至