1

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
4
  • 1
    remove the image and share text only. Commented Oct 3, 2021 at 9:16
  • @balderman i have updated code and image is for Columns reference Commented Oct 3, 2021 at 9:18
  • 1
    What is the problem? What did you try and how it failed? Where are the import statements ? How can we reproduce your code without it? Commented Oct 3, 2021 at 9:19
  • 2
    Does this answer your question? Converting to unix timestamp Python Commented Oct 3, 2021 at 9:23

1 Answer 1

1

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"))
Sign up to request clarification or add additional context in comments.

1 Comment

it works when i enter single row value but not apply for all see image 1 ibb.co/myPb0ks and image 2 ibb.co/2ckFxNC as you can see when i am calling series its not working any fix for it?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.