Your example code is wrong. This works:
import datetime
datetime.datetime.strptime("21/12/2008", "%d/%m/%Y").strftime("%Y-%m-%d")
The call to strptime() parses the first argument according to the format specified in the second, so those two need to match. Then you can call strftime() to format the result into the desired final format.
Answer from unwind on Stack OverflowYour example code is wrong. This works:
import datetime
datetime.datetime.strptime("21/12/2008", "%d/%m/%Y").strftime("%Y-%m-%d")
The call to strptime() parses the first argument according to the format specified in the second, so those two need to match. Then you can call strftime() to format the result into the desired final format.
you first would need to convert string into datetime tuple, and then convert that datetime tuple to string, it would go like this:
lastconnection = datetime.strptime("21/12/2008", "%d/%m/%Y").strftime('%Y-%m-%d')
arcpy - Python - Date notation to MM/DD/YYYY - Geographic Information Systems Stack Exchange
DATE FORMAT HELP to DD-MM-YYYY
python - Pandas, convert datetime format mm/dd/yyyy to dd/mm/yyyy - Stack Overflow
pandas - Python how to convert datetime.date to the YYYY-MM-DD? - Stack Overflow
Videos
Hello all,
I have an excel file with about 100 columns, and 30 or so are dates, I would like to convert all the date formats
from:
YYYY-MM-DD
to
M/D/YYYY
I was able to change it to MM/DD/YYYY using the following code
def fmt(input_dt):
if isnull(input_dt):
return ""
else:
return input_dt.strftime("%m/%d/%Y")
for col in df.columns:
if df[col].dtype == 'datetime64[ns]':
df[col] = df[col].apply(fmt)but that gives me
MM/DD/YYYY
I also need it to be datetime when exported back to excel.
I looked into the documentation
https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes
But it does not have M/D/YYYY any suggestions would be helpful. Thank you! Also if there is a more pythonic way to write it please let me know
You can use the parse_dates and dayfirst arguments of pd.read_csv, see: the docs for read_csv()
df = pd.read_csv('myfile.csv', parse_dates=['Date'], dayfirst=True)
This will read the Date column as datetime values, correctly taking the first part of the date input as the day. Note that in general you will want your dates to be stored as datetime objects.
Then, if you need to output the dates as a string you can call dt.strftime():
df['Date'].dt.strftime('%d/%m/%Y')
When I use again this:
df['Date'] = pd.to_datetime(df['Date']), it gets back to the previous format.
No, you cannot simultaneously have the string format of your choice and keep your series of type datetime. As remarked here:
datetimeseries are stored internally as integers. Any human-readable date representation is just that, a representation, not the underlying integer. To access your custom formatting, you can use methods available in Pandas. You can even store such a text representation in apd.Seriesvariable:formatted_dates = df['datetime'].dt.strftime('%m/%d/%Y')The
dtypeofformatted_dateswill beobject, which indicates that the elements of your series point to arbitrary Python times. In this case, those arbitrary types happen to be all strings.Lastly, I strongly recommend you do not convert a
datetimeseries to strings until the very last step in your workflow. This is because as soon as you do so, you will no longer be able to use efficient, vectorised operations on such a series.
Just put that into the str(...) function:
import datetime
my_date = datetime.date(2022, 6, 7)
print(str(my_date)) # prints 2022-06-07
Technically, you can just print it and not make it a string first. But putting it in str means that instead of printing it, you could save that string to a variable.
If you need more advanced formatting options, then you can do what @FObersteiner suggested. But the format you want happens to be the default, so this will do if you just want that one format
Try this:
# import datetime module
from datetime import datetime
# consider date in string format
my_date = "30-May-2020-15:59:02"
# convert datetime string into date,month,day and
# hours:minutes:and seconds format using strptime
d = datetime.strptime(my_date, "%d-%b-%Y-%H:%M:%S")
# convert datetime format into %Y-%m-%d-%H:%M:%S
# format using strftime
print(d.strftime("%Y-%m-%d-%H:%M:%S"))