Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

230
Visualizações
Get datetime format from string python

In Python there are multiple DateTime parsers which can parse a date string automatically without providing the datetime format. My problem is that I don't need to cast the datetime, I only need the datetime format.

Example: From "2021-01-01", I want something like "%Y-%m-%d" or "yyyy-MM-dd".

My only idea was to try casting with different formats and get the successful one, but I don't want to list every possible format.

I'm working with pandas, so I can use methods that work either with series or the string DateTime parser.

Any ideas?

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

In pandas, this is achieved by pandas._libs.tslibs.parsing.guess_datetime_format

from pandas._libs.tslibs.parsing import guess_datetime_format

guess_datetime_format('2021-01-01')

# '%Y-%m-%d'

As there will always be an ambiguity on the day/month, you can specify the dayfirst case:

guess_datetime_format('2021-01-01', dayfirst=True)
# '%Y-%d-%m'
over 4 years ago · Santiago Trujillo Relatório

0

Please see which one suits best for you:

df['Column'] = df['Column'].dt.strftime("%Y-%m-%d")

df['Column'] = pd.to_datetime(df['Column']).dt.date

df['Column'] = pd.to_datetime(df['Column']).dt.normalize()

the datatype of first two options will be object;

while the 3rd one with normalize will be datetime.

over 4 years ago · Santiago Trujillo Relatório

0

You can try this way, I am not sure though

    for col in  df.select_dtypes(include['datetime64']).columns.tolist():
        df[col] = df[col].astype(str)
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda