datetime displaying in an alternate format than the true value

I am attempting to reformat a datetime pattern within CSV files:

Original date format:

DAY/MONTH/YEAR

Desired Outcome:

YEAR/MONTH/DAY

rows = df['clock_now'] contains the following data:

22/05/2022 12:16
22/05/2022 12:20
22/05/2022 12:21
22/05/2022 12:44
22/05/2022 12:47
22/05/2022 12:47
22/05/2022 12:51

This is my full script:

import pandas as pd
import datetime

filials= [
    'base.csv',
    'max.csv'
]

for filial in filials:
    df = pd.read_csv(filial)
    rows = df['clock_now']
    for row in rows:

        change_format = datetime.datetime.strptime(row, '%d/%m/%Y %H:%M')
        final_format = change_format.strftime('%Y/%m/%d %H:%M')

        df.loc[df['clock_now'] == row, 'clock_now'] = final_format
    df.to_csv(filial, index=False)

An error is being returned stating a format issue with one of the values, although there isn't a '2022/05/22 12:47' value present in rows = df['clock_now'].

change_format = datetime.datetime.strptime(row, '%d/%m/%Y %H:%M')
File "C:\Users\Computador\AppData\Local\Programs\Python\Python310\lib\_strptime.py", line 568, in _strptime_datetime
    tt, fraction, gmtoff_fraction = _strptime(data_string, format)
File "C:\Users\Computador\AppData\Local\Programs\Python\Python310\lib\_strptime.py", line 349, in _strptime

raise ValueError("time data %r does not match format %r" %

ValueError: time data '2022/05/22 12:47' does not match format '%d/%m/%Y %H:%M'

What could be causing this issue?

Answer №1

One possible solution is to attempt the following:

dt_rows = pd.to_datetime(rows)
dt_rows = pd.Series(map(lambda dt:dt.strftime("%Y/%m/%d %H:%M"), dt_rows))

Here is the resulting output:

0    2022/05/22 12:20
1    2022/05/22 12:21
2    2022/05/22 12:44
3    2022/05/22 12:47
4    2022/05/22 12:47
5    2022/05/22 12:51
dtype: object

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What could be causing my code to loop twice when utilizing the keyboard?

Currently, I am developing a script that will notify the user when a specific sequence of numbers is inputted. The functionality appears to work correctly, however, it returns "1122334455" instead of the expected output of "12345": import sys sys.path.app ...

Running Postgres on your own computer is a straightforward process that can

After reading the documentation for Postgres in relation to Flask I learned that in order to run Postgres, it is necessary to include the following code snippet: app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = postgresql://localh ...

The Submit button cannot be selected in the SelectField

I keep encountering a "Method Not Allowed" error when I select data from a dropdown field and click on the 'Choose' button to submit. What could be causing this issue? app.py from flask import Flask, render_template, flash from flask_wtf import ...

Python: Receiving None as output when attempting to print

Why is the following code printing None? Could it be indicating that the page is not being located? import BeautifulSoup as soup import RoboBrowser br = RoboBrowser() login_url = 'https://www.cbssports.com/login' login_page = br.open(login_url ...

Can someone please explain the contrast between using str(x) and x.str in Python?

What I needed to accomplish: Replace all commas with dots in a Pandas DataFrame. My attempted solution: df.apply(lambda x: str(x).replace(",", ".")) But this resulted in an error: ValueError: Must have equal len keys and value when ...

ERROR: Cannot call the LIST object

https://i.stack.imgur.com/jOSgE.png Can someone assist me in resolving this issue with my code: "I'm getting an error message saying 'TypeError: 'list' object is not callable'" ...

TimeoutException raised with message, screen, and stacktrace

I am a beginner when it comes to Python and Selenium, and I was attempting to try out an example code that I found on YouTube. Here is the code snippet: from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver ...

Exploring how to read KMS SES-encrypted messages using boto3

I'm attempting to adapt the code from the following link to Python using boto3: https://github.com/gilt/node-s3-encryption-client/issues/3 However, I've hit a roadblock when trying to retrieve the plaintext from KMS with the code below: metadat ...

Warning message regarding the deprecation of features in selenium/geckodriver

Can you explain the meaning of the DeprecationWarning? I noticed that if I remove the "elem" functions, it seems to work. However, when the Chrome tab opens with the link, it immediately closes again. from selenium import webdriver from selenium.webdriver ...

The input speed of text using Selenium on the search field is extremely slow with IEDriverServer

Currently, I'm utilizing selenium with Python on a Windows 7 system. This is the code snippet I am using: import os from selenium import webdriver ie_driver_path = "C:\Python36\Scripts\IEDriverServer.exe" driver = webdriver.Ie(ie_dr ...

Is it possible to modify a method without altering its functionality?

I am currently attempting to verify that a pandas method is being called with specific values. However, I have encountered an issue where applying a @patch decorator results in the patched method throwing a ValueError within pandas, even though the origin ...

Uploading a file to FastAPI server with CURL: Step-by-step guide

I am in the process of configuring a FastAPI server that is capable of accepting a single file upload from the command line through the use of curl. To guide me, I am following the FastAPI Tutorial located at: from typing import List from fastapi import ...

Refreshing frequency and reattempts when using selenium on a webpage

I am currently utilizing selenium with python to download a file from a URL. from selenium import webdriver profile = webdriver.FirefoxProfile() profile.set_preference('browser.download.folderList', 2) # custom location profile.set_preference(& ...

Tips for generating skipgrams utilizing Python

When it comes to skipgrams, they are considered to be ngrams that encompass all ngrams and include each (k-i)skipgram until (k-i)==0 (which covers 0 skip grams). So, the question arises: how can one efficiently calculate these skipgrams in Python? Below i ...

Python Access Timeout Issue in Google Sheets

I have been trying to access and update a Google Spreadsheet using Python. I came across a tutorial that many people have found helpful: Here is what I have done so far: Generated the necessary credentials as per the instructions and downloaded the .jso ...

Python encountered a NameError when it was unable to locate the variable 'Y'

My goal was to create a program that generates a random number between 1 and 6. The program will continue generating numbers until the user inputs 'N'. Check out my code below: import random def roll(): min_range = 1 max_range = 6 v ...

Calculating a running total by adding the loop variable to itself

I'm struggling to figure out how to adjust my code to ensure that each time it runs the calculation, the result gets added as a cumulative sum for my variable delta_omega. Essentially, I want to continuously add up previous values in the delta_omega a ...

Calculate Total Expenses using Python

Problem: The cost of a cupcake is represented as A dollars and B cents. Calculate the total amount in dollars and cents that should be paid for N cupcakes. The program requires three inputs: A, B, N. It will output two numbers representing the total cost. ...

What is the best way to format this DateTime for a more visually appealing appearance within an Angular Material <mat-card-subtitle>?

My date looks like this: 2000-12-16T00:00:00 When displayed in Material code (as the publish_date): <mat-card *ngFor="let book of bookItems"> <mat-card-header > <mat-card-title>{{book.title | titlecase}}</mat-card-title> ...

Tips for accessing all elements of a 2D array using slicing in Python

I am trying to assign the value of G[1][0], G[1][1]... G[1][100] and G[0][1], G[1][1]... G[100][1] to be 1 G = [[0]*101]*101 G[1][:] = 1 G[:][1] = 1 However, this resulted in an error: ... G[1][:] = 1 TypeError: can only assign an iterable Is there a w ...