Home > other >  How to convert time column to Unix timestamp?
How to convert time column to Unix timestamp?

Time:10-04

enter image description here

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

CodePudding user response:

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"))
  • Related