Convert string to DateTime for mysql in python - 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/

Related

Timezone in python date string is not matching

In a script, I am converting the date string into DateTime format, so that I can modify the date, but this timezone part is showing an error.
from datetime import datetime
date_str = 'Wed, 1 Jun 2022 16:44:40 +0200 (CEST)'
temp_date = datetime.strptime(date_str, '%a, %d %b %Y %H:%M:%S %z (%Z)')
print(temp_date)
When I run this I am getting ValueEror.
ValueError: time data 'Wed, 01 Jun 2022 16:44:40 +0200 (CEST)' does not match format '%a, %d %b %Y %H:%M:%S %z (%Z)'
An extract from the datetime documentation:
strptime() only accepts certain values for %Z:
any value in time.tzname for your machine’s locale
the hard-coded values UTC and GMT
So someone living in Japan may have JST, UTC, and GMT as valid values,
but probably not EST. It will raise ValueError for invalid values
Try running the below to see if CEST is in your machine's locale:
import time
print(time.tzname)
Seeing the complexity of problem, I suggest using third party library like dateutil which can parse datetime with ease.
from dateutil.parser import parse
date_str = 'Wed, 1 Jun 2022 16:44:40 +0200 (CEST)'
temp_date = parse(date_str)
print(temp_date)
temp_date is of type datetime.datetime
https://dateutil.readthedocs.io/en/stable/

Error converting datetime string to datetime object

I get an error when I try to convert a datetime string to a datetime object:
df['R_DATE'] = pd.to_datetime(df['R_DATE'], format='%a %b %d %H:%M:%S %Z %Y')
Error is:
...
File "pandas\_libs\tslibs\strptime.pyx", line 141, in pandas._libs.tslibs.strptime.array_strptime
ValueError: time data 'Mon Oct 18 00:00:00 EDT 2021'
does not match format '%a %b %d %H:%M:%S %Z %Y' (match)
From what I can tell format appears to match the datetime string value. I'm not sure if the timezone value (EDT) is causing issues.
nvm. found the answer I was looking for.
import dateutil
tzdict = {'EST': dateutil.tz.gettz('America/New_York'),
'EDT': dateutil.tz.gettz('America/New_York')}
df['R_DATE'] = df['R_DATE'].apply(dateutil.parser.parse, tzinfos=tzdict)

How can I convert datetime to unix timestamp in python

I have one date format "Mon, 15 Jun 2020 22:11:06 PT" I want to convert this format to unix timestamp.
I am using the following code ===>
news_date = datetime.strptime(news_date, '%a, %d %b %Y %H:%M:%S %Z')
news_date = calendar.timegm(news_date.utctimetuple())
But gives the following error ===>
ValueError: time data 'Mon, 15 Jun 2020 22:11:06 PT' does not match format '%a, %d %b %Y %H:%M:%S %Z'
How can i solve it and get the unix timestamp from this?
%Z can't parse the timezone name PT - I suggest you skip parsing it and add it "manually" instead:
from datetime import datetime
import dateutil
news_date = "Mon, 15 Jun 2020 22:11:06 PT"
# parse string without the timezone:
news_date = datetime.strptime(news_date[:-3], '%a, %d %b %Y %H:%M:%S')
# add the timezone:
news_date = news_date.replace(tzinfo=dateutil.tz.gettz('US/Pacific'))
# extract POSIX (seconds since epoch):
news_date_posix = news_date.timestamp()
# 1592284266.0
if you have multiple strings with different timezones, you could use a dict to map the abbreviations to time zone names, e.g.
tzmapping = {'PT': 'US/Pacific'}
news_date = "Mon, 15 Jun 2020 22:11:06 PT"
# get appropriate timezone from string, according to tzmapping:
tz = dateutil.tz.gettz(tzmapping[news_date.split(' ')[-1]])
# parse string and add timezone:
news_date_datetime = datetime.strptime(news_date[:-3], '%a, %d %b %Y %H:%M:%S')
news_date_datetime = news_date_datetime.replace(tzinfo=tz)

How to create date timestamp logs like git log

Using datetime.datetime.now(), I receive some badly formatted timestamps.
Is there an intuitive way of creating a date timestamp in this format?
Wed Aug 7 13:38:59 2019 -0500
This is seen in git log.
You can use datetime.datetime.strftime() to format dates as shown below:
from datetime import datetime
d = '2019-08-07 13:38:59-0500'
d2 = datetime.strptime(d, '%Y-%m-%d %H:%M:%S%z')
d3 = d2.strftime('%a %b %d %H:%M:%S %Y %z')
print(d3)
This returns:
Wed Aug 07 13:38:59 2019 -050000
This website is a great resource for strftime formatting.
You can still use the datetime library. Using strftime, you can rewrite the datetime object into a nicely formatted string.
In your case, you are going for Wed Aug 7 13:38:59 2019 -0500, which translated to strftime formatting is "%a %b %d %H:%M:%S %Y %z".
Overall, it'd be
datetime.datetime.now().strftime("%a %b %d %H:%M:%S %Y %z")
Which will give a string that looks like 'Wed Aug 7 13:38:59 2019 -0500'.
I would do the following:
from time import gmtime, strftime
if __name__ == "__main__":
time = strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime())
print(time)
This was found on the documentation page of the time module. There are also a lot of additional features you might be interested in using outlined here: https://docs.python.org/3/library/time.html#time.strftime

Convert date string in excel to date object in python

I have a date in excel which is given in: dd mmm yy format i.e.,
29 Jun 18
How do I convert this string into a date object?
I get the error:
time data '13 Jul 18' does not match format '%d %m %Y'
when I try
datetime.strptime(input, '%d %m %Y')
What should the correct date format be?
Since the year in your excell is only two digits (i.e., 18 and not 2018) you need to use %y instead of %Y in your format string:
datetime.strptime(input, '%d %b %y')
For example:
datetime.strptime( '13 Jul 18', '%d %b %y')
Results with:
datetime.datetime(2018, 7, 13, 0, 0)
See this page for more information about date/time string format.
You can use python datetime module or you can use dateutil parser to parse the string date to valid datetime object. I'd go with dateutil parser as I don't have to define string format. Here is an example
from dateutil.parser import parse
dt = parse("Thu Sep 25 10:36:28 BRST 2003")
Remember to install dateutil by pip install python-dateutil
You would have to import datetime and import xlrd
Use xlrd to open the excel workbook as
book = xlrd.open_workbook("Excel.xlsx")
sheet = book.sheet_by_name("Worksheet")
Use this to convert
obj = datetime.datetime(*xlrd.xldate_as_tuple(sheet.cell(row,column).value, book.datemode))
from datetime import datetime
datetime.strptime("29 Jun 18", "%d %b %y").date()
Here you get a datetime.date object, I don't know if that's good enough for you. I recommend you to visit the documentation on the module
You can make use of strptime which follows the pattern:
datetime.strptime(date_string, format)
example:
from datetime import datetime
dt = datetime.strptime('19 Jul 2017', '%d %b %y')
Hope this helps :)
Your format is incorrect: %b is Locale's short month and %y is two digit year
import time
time.strptime('13 Jul 18', '%d %b %y')
time.struct_time(tm_year=2018, tm_mon=7, tm_mday=13, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=4, tm_yday=194, tm_isdst=-1)

Categories

Resources