problem of date conversion from english to french - python

I try to convert a date in english (2019-10-07) in french (07/10/2016)
I try
dat = '07/10/2019'
dat = time.strftime('%Y-%m-%d')
but got the result '2019-10-16' instead of '2019-10-07'

using datetime you can decide the format in which the source date is provided, and the target format you want.
from datetime import datetime
dat = '07/10/2019'
datetime.strptime(dat, "%d/%m/%Y").strftime("%Y-%m-%d")
out[6]: '2019-10-07'

strftime needs a time/date to convert, and it will use the current date and time if you don't provide one. The previous value of dat is not relevant - this information is not seen by strftime.
You need to provide the time information that strftime will format, as a tuple that you can get by parsing the original string. For this, use strptime (f for format, p for parse).
So:
dmy = '07/10/2019'
ymd = time.strftime('%Y-%m-%d', time.strptime(dmy, '%d/%m/%Y'))
# ^^^^^^^^ ^^^^^^^^
# output schema input schema
# now ymd is '2019-10-07'
(Or you can use the datetime module as in the other answer. This way, the parsing gives you an object, which has a method to format back - so you can write the whole operation "in order" on the line. But the general principle is the same: you need to parse, then format, and you need to specify the schema on each side.)

with :
dat = time.strftime('%Y-%m-%d')
you recover your actual date.
you need to make :
from datetime import datetime
dat = '07/10/2019'
dat = datetime.strptime(dat, '%m/%d/%Y')
print(dat.strftime('%Y-%m-%d') )

Related

How can I add a zero to dates in a string so all months are 2 characters? [duplicate]

Using a Python script, I need to read a CVS file where dates are formated as DD/MM/YYYY, and convert them to YYYY-MM-DD before saving this into a SQLite database.
This almost works, but fails because I don't provide time:
from datetime import datetime
lastconnection = datetime.strptime("21/12/2008", "%Y-%m-%d")
#ValueError: time data did not match format: data=21/12/2008 fmt=%Y-%m-%d
print lastconnection
I assume there's a method in the datetime object to perform this conversion very easily, but I can't find an example of how to do it. Thank you.
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.
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')
I am new to programming. I wanted to convert from yyyy-mm-dd to dd/mm/yyyy to print out a date in the format that people in my part of the world use and recognise.
The accepted answer above got me on the right track.
The answer I ended up with to my problem is:
import datetime
today_date = datetime.date.today()
print(today_date)
new_today_date = today_date.strftime("%d/%m/%Y")
print (new_today_date)
The first two lines after the import statement gives today's date in the USA format (2017-01-26). The last two lines convert this to the format recognised in the UK and other countries (26/01/2017).
You can shorten this code, but I left it as is because it is helpful to me as a beginner. I hope this helps other beginner programmers starting out!
Does anyone else else think it's a waste to convert these strings to date/time objects for what is, in the end, a simple text transformation? If you're certain the incoming dates will be valid, you can just use:
>>> ddmmyyyy = "21/12/2008"
>>> yyyymmdd = ddmmyyyy[6:] + "-" + ddmmyyyy[3:5] + "-" + ddmmyyyy[:2]
>>> yyyymmdd
'2008-12-21'
This will almost certainly be faster than the conversion to and from a date.
#case_date= 03/31/2020
#Above is the value stored in case_date in format(mm/dd/yyyy )
demo=case_date.split("/")
new_case_date = demo[1]+"-"+demo[0]+"-"+demo[2]
#new format of date is (dd/mm/yyyy) test by printing it
print(new_case_date)
If you need to convert an entire column (from pandas DataFrame), first convert it (pandas Series) to the datetime format using to_datetime and then use .dt.strftime:
def conv_dates_series(df, col, old_date_format, new_date_format):
df[col] = pd.to_datetime(df[col], format=old_date_format).dt.strftime(new_date_format)
return df
Sample usage:
import pandas as pd
test_df = pd.DataFrame({"Dates": ["1900-01-01", "1999-12-31"]})
old_date_format='%Y-%m-%d'
new_date_format='%d/%m/%Y'
conv_dates_series(test_df, "Dates", old_date_format, new_date_format)
Dates
0 01/01/1900
1 31/12/1999
The most simplest way
While reading the csv file, put an argument parse_dates
df = pd.read_csv("sample.csv", parse_dates=['column_name'])
This will convert the dates of mentioned column to YYYY-MM-DD format
Convert date format DD/MM/YYYY to YYYY-MM-DD according to your question, you can use this:
from datetime import datetime
lastconnection = datetime.strptime("21/12/2008", "%d/%m/%Y").strftime("%Y-%m-%d")
print(lastconnection)
df is your data frame
Dateclm is the column that you want to change
This column should be in DateTime datatype.
df['Dateclm'] = pd.to_datetime(df['Dateclm'])
df.dtypes
#Here is the solution to change the format of the column
df["Dateclm"] = pd.to_datetime(df["Dateclm"]).dt.strftime('%Y-%m-%d')
print(df)

How to change Day/Month/Year format to Month/Day/Year in Python

I have a column that the date is in Day/Month/Year format and it is stored in object format. How can I change it to Month/Day/Year format in python?
Here is an example: How can I change 13/3/2021 to 3/13/2021?
Simple solution is using split:
def convert_format1(s: str):
d, m, y = s.split("/")
return "/".join((m, d, y))
Or you can use datetime module to convert string to datetime object(.strptime) and vice versa(.strftime):
from datetime import datetime
def convert_format2(s: str):
source_format = "%d/%m/%Y"
destination_format = "%m/%d/%Y"
d = datetime.strptime(s, source_format)
return d.strftime(destination_format)
You can then apply these functions to your dataframe's column.
note: AFAIK .strftime() method adds zero padding to the string representation of day and month. If you don't want this behavior you have to strip it manually after that.
note: second function is safer since it checks the dates to be valid as well.
import datetime
t = datetime.date.today()
print(t.month,t.day,t.year,sep="/")
change the value inside the print should let you set yourself

Python - Converting string to datetime object

I've been trying to convert a timestamp that is a string to a datetime object. The problem is the timestamps formatting. I haven't been able to properly parse the timestamp using datetime.datetime.strptime. I could write my own little parser as its a simple problem but I was hoping to use strptime function, I just need help on the formatting.
Example
import datetime
formater = "%y-%m-%dT%H:%M:%SZ"
str_timestamp = "2021-03-13T18:27:37.60918Z"
timestamp = datetime.datetime.strptime(str_timestamp, formater)
print (timestamp)
Output
builtins.ValueError: time data '2021-03-13T18:27:37.60918Z' does not match format '%y-%m-%dT%H:%M:%SZ'
I'm clearly not symbolizing the formatter properly, the T and Z parts are what I can't account for.
y should be Y. y is for 2 digits year.
You should also take care for the milliseconds with .%f:
%Y-%m-%dT%H:%M:%S.%fZ
This format works:
formater = "%Y-%m-%dT%H:%M:%S.%fZ"
output:
2021-03-13 18:27:37.609180

How to transform datettime to Solr format in Python?

How to transform this:
'2020-01-21 12:23:54'
to this (solr format):
'2020-01-21T12:23:54.625Z' ??
If not possible, how does one directly get the dates (e.g. modified date) of files in Python directly in the Solr format (shown above) ?
You can use datetime to format dates as required by Solr (that is ISO-8601 in UTC), adding the 'Z' explicitly since isoformat() function does not include any timezone information :
from datetime import datetime
d = datetime.utcnow().isoformat(timespec='milliseconds') + 'Z'
Starting with a given date string, you can parse it with strptime then convert it to iso (assuming the date is already in utc) :
d = datetime.strptime('2020-01-21 12:23:54', '%Y-%m-%d %H:%M:%S').isoformat() + 'Z'
You should set timespec='seconds' if you don't need more precision (Solr will ignore fractions beyond milliseconds).

Converting date between DD/MM/YYYY and YYYY-MM-DD?

Using a Python script, I need to read a CVS file where dates are formated as DD/MM/YYYY, and convert them to YYYY-MM-DD before saving this into a SQLite database.
This almost works, but fails because I don't provide time:
from datetime import datetime
lastconnection = datetime.strptime("21/12/2008", "%Y-%m-%d")
#ValueError: time data did not match format: data=21/12/2008 fmt=%Y-%m-%d
print lastconnection
I assume there's a method in the datetime object to perform this conversion very easily, but I can't find an example of how to do it. Thank you.
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.
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')
I am new to programming. I wanted to convert from yyyy-mm-dd to dd/mm/yyyy to print out a date in the format that people in my part of the world use and recognise.
The accepted answer above got me on the right track.
The answer I ended up with to my problem is:
import datetime
today_date = datetime.date.today()
print(today_date)
new_today_date = today_date.strftime("%d/%m/%Y")
print (new_today_date)
The first two lines after the import statement gives today's date in the USA format (2017-01-26). The last two lines convert this to the format recognised in the UK and other countries (26/01/2017).
You can shorten this code, but I left it as is because it is helpful to me as a beginner. I hope this helps other beginner programmers starting out!
Does anyone else else think it's a waste to convert these strings to date/time objects for what is, in the end, a simple text transformation? If you're certain the incoming dates will be valid, you can just use:
>>> ddmmyyyy = "21/12/2008"
>>> yyyymmdd = ddmmyyyy[6:] + "-" + ddmmyyyy[3:5] + "-" + ddmmyyyy[:2]
>>> yyyymmdd
'2008-12-21'
This will almost certainly be faster than the conversion to and from a date.
#case_date= 03/31/2020
#Above is the value stored in case_date in format(mm/dd/yyyy )
demo=case_date.split("/")
new_case_date = demo[1]+"-"+demo[0]+"-"+demo[2]
#new format of date is (dd/mm/yyyy) test by printing it
print(new_case_date)
If you need to convert an entire column (from pandas DataFrame), first convert it (pandas Series) to the datetime format using to_datetime and then use .dt.strftime:
def conv_dates_series(df, col, old_date_format, new_date_format):
df[col] = pd.to_datetime(df[col], format=old_date_format).dt.strftime(new_date_format)
return df
Sample usage:
import pandas as pd
test_df = pd.DataFrame({"Dates": ["1900-01-01", "1999-12-31"]})
old_date_format='%Y-%m-%d'
new_date_format='%d/%m/%Y'
conv_dates_series(test_df, "Dates", old_date_format, new_date_format)
Dates
0 01/01/1900
1 31/12/1999
The most simplest way
While reading the csv file, put an argument parse_dates
df = pd.read_csv("sample.csv", parse_dates=['column_name'])
This will convert the dates of mentioned column to YYYY-MM-DD format
Convert date format DD/MM/YYYY to YYYY-MM-DD according to your question, you can use this:
from datetime import datetime
lastconnection = datetime.strptime("21/12/2008", "%d/%m/%Y").strftime("%Y-%m-%d")
print(lastconnection)
df is your data frame
Dateclm is the column that you want to change
This column should be in DateTime datatype.
df['Dateclm'] = pd.to_datetime(df['Dateclm'])
df.dtypes
#Here is the solution to change the format of the column
df["Dateclm"] = pd.to_datetime(df["Dateclm"]).dt.strftime('%Y-%m-%d')
print(df)

Categories

Resources