Search code examples
pandasdatetimecustomization

Convert a Particular Dataframe Column Into Customized Date Or Time


As you can see a Date & Time Column are being saved in this CSV File. Now what problem is that the date & time are in format of something like - 30-1-2022 & 20:08:00

But i want it to look something like 30th Jan 22 and 8:08 PM

Any code for that ?

import requests
import pandas as pd
from datetime import datetime
from datetime import date

currentd = date.today()

s = requests.Session()
headers =   {'user-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36'}
url = 'https://www.nseindia.com/'
step = s.get(url,headers=headers)

today = datetime.now().strftime('%d-%m-%Y')
api_url = f'https://www.nseindia.com/api/corporate-announcements?index=equities&from_date={today}&to_date={today}'


resp = s.get(api_url,headers=headers).json()

result = pd.DataFrame(resp)
result.drop(['difference', 'dt','exchdisstime','csvName','old_new','orgid','seq_id','sm_isin','bflag','symbol','sort_date'], axis = 1, inplace = True)
result.rename(columns = {'an_dt':'DateandTime', 'attchmntFile':'Source','attchmntText':'Topic','desc':'Type','smIndustry':'Sector','sm_name':'Company Name'}, inplace = True)
result[['Date','Time']] = result.DateandTime.str.split(expand=True)
result.drop(['DateandTime'], axis = 1, inplace = True)
result.to_csv( ( str(currentd.day) +'-'+str(currentd.month) +'-'+'CA.csv'), index=True)

print('Saved the CSV File')

Solution

  • Try creating a temporary column:

    result['Full_date']=pd.to_datetime(result['Date']+' '+result['Time'])
    

    Then format 'Date' and 'Time'

    result['Date']=result['Full_date'].dt.strftime('%b %d, %Y')
    result['Time']=result['Full_date'].dt.strftime('%R' '%p')