Python converting "March 2 2012" into a datetime object - python

When I call the following function, I get a struct_time obj. Is there a way to convert this into a date obj?
import time
date = time.strptime("March 2 2012", '%B %d %Y')
Thanks

Use
from datetime import datetime
date = datetime.strptime("March 2 2012", '%B %d %Y').date()

You can also do:
import dateutil.parser
datetime_obj = dateutil.parser.parse("March 2 2012")
edit:
this returns a datetime.datetime object, not a datetime.date object:
datetime.datetime(2012, 3, 2, 0, 0) #opposed to datetime.date(2012, 3, 2)

ds = time.strptime("March 2 2012", '%B %d %Y')
realdate = datetime.date(ds.tm_year, ds.tm_mon, ds.tm_mday)

Related

Python get valid date format from date string

Is there a way to guess datetime format of a given string in python?
e.g. desired usage would be:
> guess_format('2020-02-24 07:22')
'%Y-%m-%d %H:%M'
There's dateutil project which automates datetime string conversion to valid Datetime objects:
> from dateutil.parser import parse
> parse('2020-02-24 07:22')
datetime.datetime(2020, 2, 24, 7, 22)
but can it produce valid formatting strings?
The pydateinfer package provides the possibility to infer the datetime format string of a given date string.
Example:
>>> import dateinfer
>>> dateinfer.infer(['Mon Jan 13 09:52:52 MST 2014', 'Tue Jan 21 15:30:00 EST 2014'])
'%a %b %d %H:%M:%S %Z %Y'

Convert string to DateTime for mysql in python

I want to convert my date into DateTime object for MySQL.
My string format is: Mon Aug 27 04:47:45 +0000 2018
Expected Output: 'YYYY-M-D H:mm:ss'
from datetime import datetime
t = datetime.strptime('Mon Aug 27 04:47:45 +0000 2008', '%a %b %d %H:%M:%S % z %Y')
t.strftime('%Y-%m-%d %H:%M:%S')
Refer section 8.1.8
here
If you are using python 3, this solution would work -
from datetime import datetime
x = 'Mon Aug 27 04:47:45 +0000 2018'
x = datetime.strftime(datetime.strptime(x, '%a %b %d %I:%M:%S %z %Y'), '%Y-%m-%d %H:%M:%S')
# OP '2018-08-27 04:47:45'
But for python 2, you might get a ValueError: 'z' is a bad directive.... In that case, you'll either have to use something like pytz or dateutil. The table that you need to look for all these conversions can be found here
Edit: You can't have Expected Output: 'YYYY-M-D H:mm:ss' if you convert your datetime string to datetime object. Datetime object has it's own format. Above gives you a string of the format that you want
from datetime import datetime
date_as_dt_object = datetime.strptime(dt, '%a %b %d %H:%M:%S %z %Y')
You can use date_as_dt_object in a raw query or an ORM. If used in a raw query pass it as a string like:
query = "select * from table where date >" + str(date_as_dt_object)
Check out this list for Python's strftime directives.
http://strftime.org/

Python : string with timezone to datetime object conversion

I have a string like this
dateStr = "Wed Mar 15 12:50:52 GMT+05:30 2017"
which is IST time.
Is there any way to read the dateStr as per the specified timezone within the dateStr
i.e. GMT+05:30.
So that I can make datetime object directly.
I have tried to parse it using format
format = "%a %b %d %H:%M:%S %Z%z %Y"
But it gives me error of format does not match.
Can you try this?
>>> dateStr = "Wed Mar 15 12:50:52 GMT+05:30 2017"
>>> from dateutil.parser import parse
>>> parse(dateStr)
datetime.datetime(2017, 3, 15, 12, 50, 52, tzinfo=tzoffset(None, -19800))

Parse date with specific format in python

how would you go about parsing a date like that in python:
Monday, April 1st
I've tried
datetime_object = datetime.strptime(date.replace("st","").replace("rd","").replace("th","").replace("nd","").strip(), '%A, %B %d')
But obviously it would remove the "nd" from "Monday" and cause an exception
thanks
Don't replace. Strip, from the right using str.rstrip. If the unwanted characters don't exist, the string is returned as is:
>>> from datetime import datetime
>>> s = "Monday, April 1st"
>>> datetime.strptime(s.rstrip('strndh'), '%A, %B %d')
datetime.datetime(1900, 4, 1, 0, 0)
Note that the day information here (i.e. Monday) is redundant.
You can use the dateutil module (pip install py-dateutil):
>>> from dateutil import parser
>>> parser.parse("Monday, April 1st")
datetime.datetime(2017, 4, 1, 0, 0)
Also if all your string doesn't have the same length:
a = "Monday, April 1st"
if not a[-1].isdigit():
a = a[:-2]
datetime_object = datetime.strptime(a, '%A, %B %d')

Converting dates with times like "midnight"

I have the following string which I am trying to convert to a datetime in python
From django template I am getting the following date format:
July 1, 2013, midnight
I am trying to convert the string above into a date time format
date_object = datetime.strptime(x, '%B %d, %Y, %I:%M %p')
It throws a format error
time data 'July 1, 2013, midnight' does not match format '%B %d, %Y, %I:%M %p'
Your best shot is probably the parsedatetime module.
Here's your example:
>>> import parsedatetime
>>> cal = parsedatetime.Calendar()
>>> cal.parse('July 1, 2013, midnight')
((2013, 7, 1, 0, 0, 0, 0, 245, 0), 3)
cal.parse() returns a tuple of two items. The first is the modified parsedatetime.Calendar object, the second is an integer, as explained in the docstring of the parse method:
0 = not parsed at all
1 = parsed as a C{date}
2 = parsed as a C{time}
3 = parsed as a C{datetime}
A few words on strptime:
strptime won't be able to understand "midnight", but you can replace it with an actual hour, using something like this:
def fix_dt(raw_date):
"""Replace 'midnight', 'noon', etc."""
return raw_date.replace('midnight', '0').replace('noon', '12')
def parse_dt(raw_date):
"""Parse the fuzzy timestamps."""
return datetime.datetime.strptime(fix_dt(raw_date), '%B %d, %Y, %H')
Then:
>>> parse_dt('July 1, 2013, midnight')
datetime.datetime(2013, 7, 1, 0, 0)
You can play on strfti.me to see which one will match your format.
You should check out this other question. The answers suggest using parsedatetime and pyparsing to parse fuzzy timestamps like the one in your example. Also check this pyparsing wiki page.
You could also just combine the date withe datetime's start time:
from datetime import datetime, date
dt = date.today()
print(datetime.combine(dt, datetime.min.time()))

Categories

Resources