尝试修改脚本以采用时间戳日期格式而不是%Y-%m-%d格式[Python]

时间:2018-03-10 05:46:39

标签: python csv datetime

以时间戳格式从csv中提取日期(例如1504159200) 我将这些插入适合Y-m-d格式的脚本中。

[代码是一个庞大的LSTM脚本,所以希望原始的行和我尝试过的就足够了]

startDate = 1504159200  
endDate = 1519974000

原始行没有修改...

sd = datetime.strptime(startDate, '%Y-%m-%d')
ed = datetime.strptime(endDate, '%Y-%m-%d')

Traceback (most recent call last):
File "stocks.py", line 91, in <module>
p, n = Main(['last_vix_92_18.csv', '1504159200', '1519974000', 'D'])
File "stocks.py", line 78, in Main
P = sp.PredictDate(args[1], args[2], predPrd)
File "/home/eagle/predict/dragon/pythonml-master/Stocks/StockPredictor.py", line 282, in PredictDate
ts = DateRange(startDate, endDate, period)[::-1]
File "/home/eagle/predict/dragon/pythonml-master/Stocks/StockPredictor.py", line 30, in DateRange
sd = datetime.strptime(startDate, '%Y-%m-%d')
File "/usr/lib/python3.5/_strptime.py", line 510, in _strptime_datetime
tt, fraction = _strptime(data_string, format)
File "/usr/lib/python3.5/_strptime.py", line 343, in _strptime
(data_string, format))
ValueError: time data '1504159200' does not match format '%Y-%m-%d'

我尝试过修改代码,但下面的错误如下。

sd = datetime(int(startDate)).timestamp()
ed = datetime(int(endDate)).timestamp()  

Traceback (most recent call last):
File "stocks.py", line 91, in <module>
p, n = Main(['last_vix_92_18.csv', '1504159200', '1519974000', 'D'])
File "stocks.py", line 78, in Main
P = sp.PredictDate(args[1], args[2], predPrd)
File "/home/eagle/predict/dragon/pythonml-master/Stocks/StockPredictor.py", line 284, in PredictDate
ts = DateRange(startDate, endDate, period)[::-1]
File "/home/eagle/predict/dragon/pythonml-master/Stocks/StockPredictor.py", line 31, in DateRange
sd = datetime(int(startDate)).timestamp()
TypeError: Required argument 'month' (pos 2) not found

1 个答案:

答案 0 :(得分:2)

只需使用datetime.datetime.fromtimestamp

from datetime import datetime

datetime.fromtimestamp(1504159200)  # datetime.datetime(2017, 8, 31, 2, 0)
datetime.fromtimestamp(1519974000)  # datetime.datetime(2018, 3, 2, 2, 0)