简体   繁体   中英

How to convert time column to Unix timestamp?

在此处输入图像描述

I would like to convert Datetime column to Epoch / Unix timestamp.

import pandas as pd
import yfinance as yf
import numpy as np
import time
df = yf.download(tickers='^NSEI',period='1d',interval='15m')
df.reset_index(inplace=True)
df.rename(columns = {'Datetime':'time'}, inplace = True)
df['Date'] = df['time'].dt.strftime('%Y-%m-%d')
df['time'] = df['time'].dt.strftime("%Y-%m-%d %H:%M:%S") 
df

Use this provide function citation

def utctimestamp(ts: str, DATETIME_FORMAT: str = "%d/%m/%Y"):
    import datetime, calendar
    ts = datetime.datetime.utcnow() if ts is None else datetime.datetime.strptime(ts, DATETIME_FORMAT)
    return calendar.timegm(ts.utctimetuple())

Example code (not tested)

# Imports
import datetime, calendar

# custom function
def utctimestamp(ts: str, DATETIME_FORMAT: str = "%d/%m/%Y %H:%M:%S"):
    ts = datetime.datetime.utcnow() if ts is None else datetime.datetime.strptime(ts, DATETIME_FORMAT)
    return calendar.timegm(ts.utctimetuple())

# updated code
df = yf.download(tickers='^NSEI',period='1d',interval='15m')
df.reset_index(inplace=True)
df.rename(columns = {'Datetime':'time'}, inplace = True)
df['Date'] = df['time'].dt.strftime('%Y-%m-%d')
df['time'] = utctimestamp(df['time'].dt.strftime("%Y/%m/%d %H:%M:%S"))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM