1
def date_convert(date_to_convert):
     return dt.datetime.strptime(date_to_convert, '%a %b %d %H:%M:%S %Z %Y').strftime('%m/%d/%Y')

data['Publish Time'].apply(date_convert)

when running this it says

"" ValueError: time data 'Wed Sep 07 10:35:00 IST 2022' does not match format '%a %b %d %H:%M:%S %Z %Y' ""

FObersteiner
  • 22,500
  • 8
  • 42
  • 72

1 Answers1

1

I'm unable to replicate the issue you're facing with the exact same code you've provided.

import datetime as dt

def date_convert(date_to_convert: str) -> str:
    return (dt.datetime.strptime(
                date_to_convert,'%a %b %d %H:%M:%S %Z %Y').
            strftime('%m/%d/%Y'))

date_convert('Wed Sep 07 10:35:00 IST 2022')  # 09/07/2022

However, you can also accomplish the task using the builtin dateutil library.

import dateutil

def date_convert(date_to_convert: str) -> str:
    return dateutil.parser.parse(date_to_convert).strftime('%m/%d/%Y')

date_convert('Wed Sep 07 10:35:00 IST 2022')  # 09/07/2022
Abirbhav G.
  • 369
  • 3
  • 14
  • Will this method also applied to a column as well? – vikas purohit Sep 21 '22 at 05:56
  • You can apply it to a Pandas DF column sure. It's just like any other method in Python – Abirbhav G. Sep 21 '22 at 06:00
  • When applying to column it gives C:\Users\vikas.raj\Anaconda3\lib\site-packages\dateutil\parser\_parser.py:1201: UnknownTimezoneWarning: tzname IST identified but not understood. Pass `tzinfos` argument in order to correctly return a timezone-aware datetime. In a future version, this will raise an exception. warnings.warn("tzname {tzname} identified but not understood. " --------------------------------------------------------------------------- ValueError: ('Unknown string format:', 'Defence') – vikas purohit Sep 21 '22 at 06:41
  • This might just happen to be working on *your* system if your local time zone is IST. %Z does not parse arbitrary tz abbreviations (in fact most parsers won't - abbreviations are ambitious!). To use dateutil correctly here, you'll have to define a `tzinfos` dictionary (mapping tz abbreviations to IANA tz names). – FObersteiner Sep 21 '22 at 06:59
  • @FObersteiner I was unaware of it being locale dependent. Noted – Abirbhav G. Sep 21 '22 at 07:02
  • @AbirbhavG. it's also platform-dependend, do make it even worse ;-) oh and I meant "tz abbreviations are ambiguous", not ambitious. I love auto-correction ^^ – FObersteiner Sep 21 '22 at 07:18
  • btw. here's an example of how to use the tzinfos dict: https://stackoverflow.com/a/69673614/10197418 – FObersteiner Sep 21 '22 at 07:24