How to change to datetime format date with dashes? - python

I have a date in format 2022-12-16T16-48-47" and I would like to change it to datetime using function pd.to_datetime.
My first idea was to create split the string to have it in more readable way:
string = "2022-12-16T16-48-47"
date, hour = string.split("T")
string = date + " " + hour
string
And now to use:
import pandas as pd
pd.to_datetime(string, format = "%Y-%M-%D %h-%m-%S")
But I have error:
ValueError: 'D' is a bad directive in format '%Y-%M-%D %h-%m-%S'
Do you know how it should be done properly?

Use Y, m, d and H, M, S instead:
>>> pd.to_datetime(string, format = "%Y-%m-%d %H-%M-%S")
Timestamp('2022-12-16 16:48:47')
>>>
You should check out the strftime format codes documentation for better understanding.

Related

How to convert string 2021-09-30_1 to datetime

How can I convert string 2021-09-30_1 to datetime 2021/09/30 00:00, which means that from the last string we have to substract one to get the hour.
I tried datetime.strptime(date, '%Y %d %Y %I')
datetime.strptime if to define the timestamp from a string, the format should match the provided one. datetime.strftime (note the f) is to generate a string from a datetime object.
You can use:
datetime.strptime(date, '%Y-%m-%d_%H').strftime('%Y/%m/%d %H:%M')
output: '2021/09/30 01:00'
in case the _x defines a delta:
from datetime import datetime, timedelta
d, h = date.split('_')
d = datetime.strptime(d, '%Y-%m-%d')
h = timedelta(hours=int(h))
(d-h).strftime('%Y/%m/%d %H:%M')
output: '2021/09/29 23:00'
Considering the _1 is hour and appears in al of your data (The hour part takes value between [1, 24]), your format was wrong.
For reading the date from string you'll need format it correctly:
from datetime import datetime, timedelta
date = "2021-09-30_1"
date_part, hour_part = date.split("_")
date_object = datetime.strptime(date_part, '%Y-%m-%d') + timedelta(hours=int(hour_part) - 1)
Now you have the date object. And you can display it as:
print(date_object.strftime('%Y/%m/%d %H:%M'))
from datetime import datetime
raw_date = "2021-09-30_1"
date = raw_date.split("_")[0]
parsed_date = datetime.strptime(date, '%Y-%m-%d')
formated_date = parsed_date.strftime('%Y/%m/%d %H:%M')
strptime is used for parsing string and strftime for formating.
Also for date representation you should provide format codes for hours and minutes as in:
formated_date = parsed_date.strftime('%Y/%m/%d %H:%M')

How to change a datetime format in python?

How can one make 2020/09/06 15:59:04 out of 06-09-202015u59m04s.
This is my code:
my_time = '06-09-202014u59m04s'
date_object = datetime.datetime.strptime(my_time, '%d-%m-%YT%H:%M:%S')
print(date_object)
This is the error I receive:
ValueError: time data '06-09-202014u59m04s' does not match format '%d-%m-%YT%H:%M:%S'
>>> from datetime import datetime
>>> my_time = '06-09-202014u59m04s'
>>> dt_obj = datetime.strptime(my_time,'%d-%m-%Y%Hu%Mm%Ss')
Now you need to do some format changes to get the answer as the datetime object always prints itself with : so you can do any one of the following:
Either get a new format using strftime:
>>> dt_obj.strftime('%Y/%m/%d %H:%M:%S')
'2020/09/06 14:59:04'
Or you can simply use .replace() by converting datetime object to str:
>>> str(dt_obj).replace('-','/')
'2020/09/06 14:59:04'
As your error says what you give does not match format - %d-%m-%YT%H:%M:%S - means you are expecting after year: letter T hour:minutes:seconds when in example show it is houruminutesmsecondss without T, so you should do:
import datetime
my_time = '06-09-202014u59m04s'
date_object = datetime.datetime.strptime(my_time, '%d-%m-%Y%Hu%Mm%Ss')
print(date_object)
Output:
2020-09-06 14:59:04
You need to always make sure that your desired date format should match up with your required format.
from datetime import datetime
date_object = datetime.strptime("06-09-202015u59m04s", '%d-%m-%Y%Hu%Mm%Ss')
print(date_object.strftime('%Y/%m/%d %H:%M:%S'))
Output
2020/09/06 15:59:04

time data does not match format '%Y-%m-%d %H:%M:%S'

I got this code but i keep getting this error:
time data "'2019-05-23 11:42:35'" does not match format '%Y-%m-%d %H:%M:%S'
Can someone help me.
df_conv['conversation_raw'].loc[3]
'2019-05-23 11:41:59', '2019-05-23 11:38:57', '2019-05-23 11:31:16'
f = datetime.strptime(df_conv['conversation_raw'].loc[3], '%Y-%m-%d %H:%M:%S')
error: time data "'2019-05-23 11:42:35'" does not match format '%Y-%m-%d %H:%M:%S'
Remove the single quotes (') characters from your datetime string ("'2019-05-23 11:42:35'").
Try:
f = datetime.strptime(df_conv['conversation_raw'].loc[0].replace("'",""), '%Y-%m-%d %H:%M:%S')
For multiple datetime strings, try:
f = [datetime.strptime(x.replace("'",""),'%Y-%m-%d %H:%M:%S') for x in df_conv['conversation_raw'].loc[0].split(", ")]
Use the built-in to_datetime - it parses the strings correctly, even though there are additional quotes:
import pandas as pd
pd.to_datetime("'2019-05-23 11:42:35'")
Out[1]: Timestamp('2019-05-23 11:42:35')
I used the infer_datetime_format=True so Pandas will automatically choose the right format for you like so:
dft["Datetime"] = pd.to_datetime(dft["Datetime"],infer_datetime_format=True)
Try
f = datetime.strptime(df_conv['conversation_raw'].loc[3], "'%Y-%m-%d %H:%M:%S'")

How to extract date from the string format timestamp?

I want to extract the date (eg.2018-07-16) from strings (eg. 2018-07-16 10:17:53.460035).
The strings have two formats: "2018-07-16 10:17:53.460035" and "2018-05-20 14:37:21".
When I use strptime(d, "%Y-%m-%d %H:%M:%S.%f") to convert the strings before extracting the date, it pops this error:
ValueError: time data '2018-05-20 14:37:21' does not match format
%Y-%m-%d %H:%M:%S.%f'
How can I convert both time formats to DateTime type and extract date from it?
Use to_datetime from pandas.
import pandas as pd
a = "2018-07-16 10:17:53.460035"
b = "2018-05-20 14:37:21"
print(pd.to_datetime(a).date())
print(pd.to_datetime(b).date())
You don't need the .%f at the end for the first format, that is what is causing the format error.
t = "2018-05-20 14:37:21"
strptime(t, "%Y-%m-%d %H:%M:%S")
You need to create a second format for the other time string:
t = "2018-07-16 10:17:53.460035"
strptime(t, "%Y-%m-%d %H:%M:%S.%f")
Edit: Here is another example which excepts both
time_stamps = ["2018-05-20 14:37:21", "2018-07-16 10:17:53.460035"]
for stamp in time_stamps:
fmt = "%Y-%m-%d %H:%M:%S"
try:
time = datetime.datetime.strptime(stamp, fmt+".%f")
except ValueError:
time = datetime.datetime.strptime(stamp, fmt)
print(time)

Python parse string date [duplicate]

This question already has answers here:
Convert timestamps with offset to datetime obj using strptime
(4 answers)
Closed 3 years ago.
I have string like this:
2019-04-03 05:10:35+03:00
I need to output date like this:
2019-04-03 08:10:35
My code:
print(datetime.strptime(str("2019-04-03 05:10:35+03:00"), "%Y-%m-%d %H:%M:%S%z"))
but I have error:
ValueError: time data '2019-04-03 05:10:35+03:00' does not match
format '%Y-%m-%d %H:%M:%S%z'
This will work
from datetime import datetime
your_date = datetime.strptime("2019-04-03 05:10:35+03:00", "%Y-%m-%d %H:%M:%S%z")
print(your_date.strftime("%Y-%m-%d %H:%M:%S"))
EDIT:
You have "+03:00" if you count timezone, if you want to add that to your result, do it like this:
from datetime import datetime
your_date = datetime.strptime("2019-04-03 05:10:35+03:00", "%Y-%m-%d%H:%M:%S%z")
print((your_date + timedelta(0, your_date.tzinfo.utcoffset(your_date).seconds)).strftime("%Y-%m-%d %H:%M:%S"))
The problem is that your input string is improperly formatted. %z expects a string of format +HHMM or -HHMM; you have an extra :.
Accordingly, you could use a regex to format it:
import re
source = '2019-04-03 05:10:35+03:00'
formatted = re.sub(r'([+-])(\d\d):(\d\d)', r'\1\2\3', source)
print(datetime.strptime(formatted, "%Y-%m-%d %H:%M:%S%z").astimezone(timezone.utc).strftime("%Y-%m-%d %H:%M:%S"))
Output:
2019-04-03 02:10:35
Using datetime and split() for str manipulation:
Assuming it to be + hours:
from datetime import datetime, timedelta
dt_1 = "2019-04-03 05:10:35+03:00"
date_ = dt_1.split("+")[0]
time_ = date_.split(" ")[1]
to_add = dt_1.split("+")[1]
d = datetime.strptime(date_, "%Y-%m-%d %H:%M:%S")
t = datetime.strptime(time_, "%H:%M:%S")
d += timedelta(hours=int(to_add.split(":")[0]), minutes=int(to_add.split(":")[1]))
print(d)
OUTPUT:
2019-04-03 08:10:35

Categories