Python parse string date [duplicate] - python

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

Related

How to change to datetime format date with dashes?

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.

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

Converting month in number to word [duplicate]

This question already has answers here:
Parse date string and change format
(10 answers)
Closed 4 years ago.
i have string
date = "2018-09-12"
i want to get output like 2018-September-12
and i try like this
from datetime import datetime
date3 = datetime.strptime(date, '%Y-%m%B-%d')
or date3 = datetime.strptime(date, '%Y-%B-%d')
but always get time data '2018-09-12' does not match format '%Y-%m%B-%d'
Use strftime
Ex:
from datetime import datetime
date = "2018-09-12"
date3 = datetime.strptime(date, '%Y-%m-%d').strftime("%Y-%B-%d")
print(date3)
Output:
2018-September-12
strptime to convert string datetime to datetime object.
strftime to convert datetime object to required string format.

how to convert date string(2016/5/7/ 4:25:00 PM) to date format to (2016-05-07 4:25:00) in python [duplicate]

This question already has answers here:
How to print a date in a regular format?
(25 answers)
Closed 6 years ago.
having trouble converting this string into a datetime this is what I tried so far in code:
import datetime
mystring = '2016/5/7/ 4:25:00 PM'
dateobj = datetime.datetime.strptime(mystring, "%Y-%B-%dT%H:%M:%S-%H:%M")
print (dateobj)
it throws me errors and I search in the library and still can't figure it out what I have wrong in my format.
Please any help I'll gratly apreciate it
You can do it as:
import datetime
mystring = '2016/5/7 4:25:00 PM'
dateobj = datetime.datetime.strptime(mystring, "%Y/%m/%d %I:%M:%S %p")
dateobj
Out[1]: datetime.datetime(2016, 5, 7, 16, 25)
dateobj1 = datetime.datetime.strptime(mystring, "%Y/%m/%d %I:%M:%S %p").strftime("%Y-%m-%d %I:%M:%S")
dateobj1
Out[2]: '2016-05-07 04:25:00'
The issue you are having is that in order to convert a date object you first have to create a date object. This means that your formatting will have to match the current string format '2016/5/7 4:25:00 PM' = "%Y/%m/%d %H:%M:%S %p". So we can now create a date obj and then format it using strftime with your new format "%Y-%B-%dT%H:%M:%S-%H:%M".
import datetime
mystring = '2016/5/7 4:25:00 PM'
dateobj = datetime.datetime.strptime(mystring, "%Y/%m/%d %H:%M:%S %p")
dateobj = datetime.datetime.strftime(dateobj, "%Y-%B-%dT%H:%M:%S-%H:%M")
print (dateobj)
the output recieved is a little funky, but it matches your format perfectly. Visit the datetime library to view the format codes and read up on strptime vs strftime. Good luck.
Output: 2016-May-07T04:25:00-04:25
I'm not sure where your format string came from, but it's wrong. It doesn't match your string format at all.
Take a look at the available options in the documentation.
You want this:
dateobj = datetime.datetime.strptime(mystring, "%Y/%m/%d/ %I:%M:%S %p")
This will get you a date object. You can then do this to reformat it how you want:
dateobj.strftime("%Y-%m-%d %I:%M:%S")
A couple things that were wrong with yours:
You used %H twice. This resulted in an error saying it'd be redefined.
%B is full month name (ie. January). You have a numeral.
The -s are incorrect since you have /s.
The T is not in your string at all.
Easily with dateutil.parser.parse
>>> from dateutil.parser import parse
>>> d = parse('2016/5/7/ 4:25:00 PM')
>>> d.strftime("%Y-%B-%dT%H:%M:%S-%H:%M")
'2016-May-07T16:25:00-16:25'
>>> d.strftime("%Y-%m-%d %I:%M:%S")
'2016-05-07 04:25:00'

convert string to date type python [duplicate]

This question already has answers here:
Python date string to date object
(9 answers)
Closed 9 years ago.
How do I convert a string to a date object in python?
The string would be: "30-01-12" (corresponding to the format: "%d-%m-%y")
I don't want a datetime.datetime object, but rather a datetime.date
You still use datetime.datetime but then request just the .date() portion:
datetime.datetime.strptime('30-01-12', '%d-%m-%y').date()
Demonstration:
>>> import datetime
>>> datetime.datetime.strptime('30-01-12', '%d-%m-%y').date()
datetime.date(2012, 1, 30)
This should work:
import datetime
s = "30-01-12"
slist = s.split("-")
sdate = datetime.date(int(slist[2]),int(slist[0]),int(slist[1]))
from datetime import datetime,date
date_str = '30-01-12'
formatter_string = "%d-%m-%y"
datetime_object = datetime.strptime(date_str, formatter_string)
date_object = datetime_object.date()

Categories