How to parse date time string with offset? - python

I am trying to parse this string:
string_date = "2020-10-06T12:31:15-05:00"
dt = datetime.datetime.strptime(string_date, '%Y-%m-%d %H:%M:%S %Z')
But, it doesn't work. However, I am not sure how to properly put this into a datetime object. How would I do this?

Your:
string_date = "2020-10-06T12:31:15-05:00"
seems like ISO format for me, so I did:
import datetime
string_date = "2020-10-06T12:31:15-05:00"
dt = datetime.datetime.fromisoformat(string_date)
print(dt)
print(dt.tzinfo)
Output:
2020-10-06 12:31:15-05:00
UTC-05:00
Is above what are you looking for?

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

The time data does not match format

Hello I am trying to convert a string which is a = "2019-04-22 00:00" to a datetime but it does not work, I tried this :
a = datetime.datetime.strptime(a, '%Y-%m-%d %H:%M')
But I got
time data 'start_period' does not match format '%Y-%m-%d %H:%M'
I precise start_period is get by this : a = request.POST.get('start_period')
Like this it should work:
import datetime
start_period = "2019-04-22 00:00"
a = datetime.datetime.strptime(start_period, '%Y-%m-%d %H:%M')
Result:
datetime.datetime(2019, 4, 22, 0, 0)
May I suggest using dateutil module, where you do not need to provide the format string
from dateutil import parser
print(parser.parse("2019-04-22 00:00"))
#2019-04-22 00:00:00
there are multiple ways to convert string to datetime in python. it is based on the requirement of the user which function to use.
one possible solution could be as given below.
import timestring
start_period = "2019-04-22 00:00"
print(timestring.Date(start_period))

How to convert a date string with both Etc/GMT into Python date time?

Apple is returning a strange format for the expiration date of a receipt:
2018-06-18 15:03:55 Etc/GMT
from datetime import datetime
dt = datetime.strptime('2018-06-18 15:03:55 Etc/GMT', '%Y-%m-%d %H:%M:%S %Z')
Etc and GMT are both the same.
I have tried to convert it like this into a datetime object, but failed doing so.
ValueError: time data '2018-06-18 15:03:55 Etc/GMT' does not match format '%Y-%m-%d %H:%M:%S %Z'
Why are there two time zones defined in the first place? And how can I make Python understanding it?
Actually, Etc/GMT appears to be a valid, existing time zone, just datetime does not seem to recognize it. You can do the following if you have the possibility to install pytz:
from datetime import datetime
import pytz
dt, tz = '2018-06-18 15:03:55 Etc/GMT'.rsplit(maxsplit=1) # rsplit() for simplicity, obviously re would make this safer
dto = datetime.strptime(dt, '%Y-%m-%d %H:%M:%S').replace(tzinfo=pytz.timezone(tz))
print(dto) # result: 2018-06-18 15:03:55+00:00
I am not sure if this is the correct approach..but if it helps.
import re
from dateutil.parser import parse
s = '2018-06-18 15:03:55 Etc/GMT'
print( parse(re.sub("(?<=:\d{2}\s).*\/", r"", s)) )
Output:
2018-06-18 15:03:55+00:00
I am using regex to remove Etc/ from the src datetime
Using dateutil to convert to datetime object.

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'

Categories