How can I convert text to DateTime? - python

I scraped a website and got the following Output:
2018-06-07T12:22:00+0200
2018-06-07T12:53:00+0200
2018-06-07T13:22:00+0200
Is there a way I can take the first one and convert it into a DateTime value?

Just parse the string into year, month, day, hour and minute integers and then create a new date time object with those variables.
Check out the datetime docs

You can convert string format of datetime to datetime object like this using strptime, here %z is the time zone :
import datetime
dt = "2018-06-07T12:22:00+0200"
ndt = datetime.datetime.strptime(dt, "%Y-%m-%dT%H:%M:%S%z")
# output
2018-06-07 12:22:00+02:00

The following function (not mine) should help you with what you want:
df['date_column'] = pd.to_datetime(df['date_column'], format = '%d/%m/%Y %H:%M').dt.strftime('%Y%V')
You can mess around with the keys next to the % symbols to achieve what you want. You may, however, need to do some light cleaning of your values before you can use them with this function, i.e. replacing 2018-06-07T12:22:00+0200 with 2018-06-07 12:22.

You can use datetime lib.
from datetime import datetime
datetime_object = datetime.strptime('Jun 1 2005 1:33PM', '%b %d %Y %I:%M%p')
datetime.strptime documentation
Solution here

Related

Datetime still showing time component

I have this line of code-
future_end_date = datetime.strptime('2020/02/29','%Y/%m/%d')
and when I print this-
2020-02-29 00:00:00
it still shows the time component even though I did strptime
This is because strptime returns datetime rather than date. Try converting it to date:
datetime.strptime('2020/02/29','%Y/%m/%d').date()
datetime.strptime(date_string, format) function returns a datetime
object corresponding to date_string, parsed according to format.
When you print datetime object, it is formatted as a string in ISO
8601 format, YYYY-MM-DDTHH:MM:SS
So you need to convert the datetime into date if you only want Year, month and Day -
datetime.strptime('2020/02/29','%Y/%m/%d').date()
Another possible way is using strftime() method which returns a string representing date and time using date, time or datetime object.
datetime.strptime('2020/02/29','%Y/%m/%d').strftime('%Y/%m/%d')
Output of both code snippets -
2020/02/29

format 01-01-16 7:43 string to datetime

I have the following strings that I'd like to convert to datetime objects:
'01-01-16 7:43'
'01-01-16 3:24'
However, when I try to use strptime it always results in a does not match format error.
Pandas to_datetime function nicely handles the automatic conversion, but I'd like to solve it with the datetime library as well.
format_ = '%m-%d-%Y %H:%M'
my_date = datetime.strptime("01-01-16 4:51", format_)
ValueError: time data '01-01-16 4:51' does not match format '%m-%d-%Y %H:%M'
as i see your date time string '01-01-16 7:43'
its a 2-digit year not 4-digit year
that in order to parse through a 2-digit year, e.g. '16' rather than '2016', a %y is required instead of a %Y.
you can do that like this
from datetime import datetime
datetime_str = '01-01-16 7:43'
datetime_object = datetime.strptime(datetime_str, '%m-%d-%y %H:%M')
print(type(datetime_object))
print(datetime_object)
give you output 2016-01-01 07:43:00
First of all, if you want to match 2016 you should write %Y while for 16 you should write %y.
That means you should write:
format_ = '%m-%d-%y %H:%M'
Check this link for all format codes.

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.

replace hours in a datetime type python

I have a datetime type mydate in %Y-%m-%dT%H:%M:%S format.
I want to replace the hours
I did this using mydate.replace() method
Now I want to comapre it with another specific date -> myNEWdate whose format is %Y-%m-%d %H:%M:%S :
newdate = mydate.replace(hour = islot)
print newdate
appointmentDict[mydate]['time_start'] = datetime.strptime(str(newdate),"%Y/%m/%d %H:%M:%S")
The date is printed as 2015-06-26 08:00:00
and I get the error
ValueError: time data '2015-06-26 08:00:00' does not match format '%Y/%m/%d %H:%M:%S'
What should I do to resolve this
You need to set the correct format
datetime.strptime(str(newdate),"%Y-%m-%d %H:%M:%S")
To solve the exception. Although converting from datetime 2 string and backwards doesn't make much sense, as mentioned in the comments.

OpenERP 6.1 datetime formatting

Why does
o.create_order.strftime("%d %B %Y")
returns nothing when
time.strftime("%d %B %Y")
returns the date "10 february 2013"???
o.create_order is a timestamp according to postgresql.
It contains "30/11/2012 09:38:34" as seen on the openErp sale order - Other information tab.
It is stored as "2012-11-30 08:38:34.272" when querying the database.
So I would expect to see "30 November 2012" but get nothing instead.
Am I misinterpreting the syntax?
I tested this from python 3.3:
>>> d1=datetime.datetime.today()
>>> print(d1.strftime("%d %B %Y"))
10 february 2013
How do I get it to work in OpenOffice Writer?
And by the way how do I get "February" instead of "february"?
Because o.create_order returns a string and not a datetime object, even if, internally, the database column is a timestamp. The OpenERP ORM returns a string in ISO 8601 format.
You need to use the formatLang method which is available in RML reports or create a datetime object using the datetime python module.
Try this:
datetime.strftime('%d %B %Y', o.create_order')
It is because o.create_order returns a string. So first you have to convert your string date into datetime format and then again you can convert it into any format you want as a string.
Try this:
#Converts string into datetime format.
dt1 = datetime.strptime(o.create_order,"%Y-%m-%d %H:%M:%S")
#Converts datetime into your given formate and returns string.
dt2 = datetime.strftime(dt,"%d %B %Y")
Hope this will solve your problem.

Categories