Custom date string to Python date object - python

I am using Scrapy to parse data and getting date in Jun 14, 2016
format, I have tried to parse it with datetime.strftime but
what approach should I use to convert custom date strings and what to do in my case.
UPDATE
I want to parse UNIX timestamp to save in database.

Something like this should work:
import time
import datetime
datestring = "September 2, 2016"
unixdatetime = int(time.mktime(datetime.datetime.strptime(datestring, "%B %d, %Y").timetuple()))
print(unixdatetime)
Returns: 1472792400

Related

How to compare date in python? I have a month date year format and want to compare to the current date (within 7 days)

This is the data that is being returned from my API:
"Jun 02, 2021, 2 PMEST"
If I'm within 7 days of the current date which I'm getting by doing this:
from datetime import date
today = date.today()
print("Today's date:", today)
Just need to convert Jun to a number and 02 and compare to see if it's within 7 days in the future of the current date, then return True
APPROACH 0:
Given the format of your example data, you should be able to convert it to a datetime using this code:
datetime.strptime("Jun 02, 2021, 2 PMEST", "%b %d, %Y, %I %p%Z")
The details about this format string are here: https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior
However, when I tested this locally, it worked for this input:
"Jun 02, 2021, 2 PMUTC"
but not for your input (which has different timezone):
"Jun 02, 2021, 2 PMEST"
I have investigated this some more and "read the docs" (https://docs.python.org/3/library/time.html).
To get EST parsing to work, you would have to change your OS timezone and reset the time module's timezones like this:
from datetime import datetime
import os
import time
os.environ["TZ"] = "US/Eastern". # change timezone
time.tzset(). # reset time.tzname tuple
datetime.strptime("Jun 02, 2021, 2 PMEST", "%b %d, %Y, %I %p%Z")
When you're done, be safe and delete the "hacked" environment variable:
del os.environ["TZ"]
Note - Since your system timezone is presumably still UTC, it can still parse UTC timezone too.
See this thread for detailed discussion: https://bugs.python.org/issue22377
Also note that the timestamp is not actually captured. The result you get with EST and UTC is a naive datetime object.
APPROACH 1
So, it seems like there is a better way to approach this.
First, you need to pip install dateutils if you don't already have it.
THen do something like this:
from dateutil import parser
from dateutil.tz import gettz
tzinfos = {"EST": gettz("US/Eastern")}
my_datetime = parser.parse("Jun 02, 2021, 2 PM EST", tzinfos=tzinfos)
What's happening here is we use gettz to get timezone information from the timezones listed in usr/share/zoneinfo. Then the parse function can (fuzzy) parse your string (no format needs to be specified!) and returns my_datetime which has timezone information on it. Here are the parser docs: https://dateutil.readthedocs.io/en/stable/parser.html
I don't know how many different timezones you need to deal with so the rest is up to you. Good luck.
Convert the date to a datetime structure and take the direct difference. Note that today must be a datetime, too.
import datetime
date_string = "Jun 02, 2021, 2 PMEST"
today = datetime.datetime.today()
date = datetime.datetime.strptime(date_string,
"%b %d, %Y, %I %p%Z") # Corrected
(date - today).days
#340

how to convert date to mysql format in python

How to convert date to mysql date format like Dec 21, 2019 to 2019-12-21 in python.
Please help, I am new to python.
i tried date.strftime("%Y-%m-%d %H:%M:%S") but its won't work.
You need to provide the correct format string.
import datetime
d = datetime.datetime.strptime("Dec 21, 2019","%b %d, %Y")
d.strftime("%Y-%m-%d")
If you're not sure about the format of date and/or expecting multiple formats, you can use the below code snippet
from dateutil.parser import parse
d = parse("Dec 21, 2019")
d.strftime("%Y-%m-%d")
Example snippet for date conversion.
from datetime import datetime
oldformat = 'Dec 21, 2019'
datetimeobject = datetime.strptime(oldformat,'%b %d, %Y')
newformat = datetimeobject.strftime('%Y-%m-%d')
print(newformat)

how to converting sting into dateobject for date comparison?

I am facing trouble while converting string into dateobject in python.
I want to convert string '10 JAN 2016" to dateobject so that i can compare it to the present date and get the time difference.
I tired but i am getting formatting error.What is the solution to this problem?
Use the datetime module.
import datetime
date = datetime.datetime.strptime('10 jan 2016`,'%d %b %Y').date()
difference_in_dates = date - datetime.date.today() #this returns a timedelta object
Use datetime.timedelta objects for comparison.
You can look up the documentation about the formats (%d, %m, etc.) here
You need to use a valid format.
Try looking here: https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior
dt = '10 JAN 2016'
dtime = datetime.datetime.strptime(dt, "theformat")

Convert a particular timestamp with Python 2.7.x

I have a timestamp like:
2014-01-01T05:00:00.000Z
How do I convert this so that I can easily get the month like "January"? And in general convert it to a nice format like:
January 1st, 2014
You can use datetime module. datetime.datetime expects a time string and its formatting and returns a datetime.datetime object, on which you can call strftime() to format it according to your needs.
>>> import datetime
>>> my_date = datetime.datetime.strptime("2014-01-01T05:00:00.000Z", "%Y-%m-%dT%H:%M:%S.%fZ")
>>> my_date.strftime('%d.%m.%Y')
01.01.2014
>>> date.strftime('%H:%M:%S %d.%m.%Y')
'05:00:00 01.01.2014'
There is also a python-dateutils module, which can do the same.
The strftime() method in datetime modulecan achieve this. It expects a string pattern explaining how you want to format your date.
import datetime
today = datetime.date.today()
print today.strftime('It is %d %b %Y')
The above code prints something like "It is 12 Nov 2015"
You can find more format codes at https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior

How do I convert dates from "Month DD,YY" to "MM/DD/YY" in python?

How do I convert April 28,2015 to 04/28/15 in python?
I can assign April = 4 but not April 04. How do I do that?
C:> pip install python-dateutil
C:> python
...
>>> from dateutil.parser import parse
>>> print "STACK OVERFLOW SAVED MY BACON ON:",parse("April 28,2015").strftime("%m/%d/%y")
If you are sure of the format, you could of course specify exactly:
>>> import datetime
>>> print datetime.datetime.strptime("%B %d,%Y","April 28,2015").strftime("%m/%d/%y")
The standard module datetime includes this functionality. The below code sets a string to the date in question. I then create a date/time object from the string using strptime. I then output the date from the object in the requested format.
from datetime import datetime
dt = 'April 28, 2015'
dtObject = datetime.strptime(dt,"%B %d, %Y")
dtConverted = dtObject.strftime("%m/%d/%y")
This assumes both the input and desired output are text:
import datetime
>>> datetime.datetime.strptime('April 28, 2015', '%B %d, %Y').strftime('%m/%d/%y')
'04/28/15'
The other formats are here.

Categories

Resources