Python, Convert 9 tuple UTC date to MySQL datetime format - python

I am parsing RSS feeds with the format as specified here: http://www.feedparser.org/docs/date-parsing.html
date tuple (2009, 3, 23, 13, 6, 34, 0, 82, 0)
I am a bit stumped at how to get this into the MySQL datetime format (Y-m-d H:M:S)?

tup = (2009, 3, 23, 13, 6, 34, 0, 82, 0)
import datetime
d = datetime.datetime(*(tup[0:6]))
#two equivalent ways to format it:
dStr = d.isoformat(' ')
#or
dStr = d.strftime('%Y-%m-%d %H:%M:%S')

Related

How to update Python datetime object with timezone offset given in such format: "+0300"?

Given a datetime.datetime object like that:
datetime.datetime(2022, 2, 22, 9, 24, 20, 386060)
I get client timezone offset in such format: "+0300" and need to represent the datetime.datetime object considering this offset.
For example, the object above should look like this:
datetime.datetime(2022, 2, 22, 12, 24, 20, 386060)
IIUC, you have a datetime object that represents UTC and want to convert to a UTC offset of 3 hours. You can do that like
import datetime
dt = datetime.datetime(2022, 2, 22, 9, 24, 20, 386060)
# assuming this is UTC, we need to set that first
dt = dt.replace(tzinfo=datetime.timezone.utc)
# now given the offset
offset = "+0300"
# we can convert like
converted = dt.astimezone(datetime.datetime.strptime(offset, "%z").tzinfo)
>>> converted
datetime.datetime(2022, 2, 22, 12, 24, 20, 386060, tzinfo=datetime.timezone(datetime.timedelta(seconds=10800)))

converting an array of unixtime to mmddyy on python

I have an array of unixtime timestamps. How do I convert that using
datetime.utcfromtimestamp().strftime("%Y-%M-%D %H:%M:%S")
? My array is saved under "time". How do I utilize that array in this conversion?
Assuming your times are of the format datetime, you can loop through the list and convert each one.
Here is a quick example:
import datetime
time = []
for i in range(10):
time.append(datetime.datetime.now())
print(time) # output: [datetime.datetime(2020, 7, 8, 10, 7, 4, 314614), datetime.datetime(2020, 7, 8, 10, 7, 4, 314622)....
formattedTime = []
for t in time:
formattedTime.append(t.strftime('%Y-%m-%d %H:%M:%S'))
print(formattedTime) # output: ['2020-07-07/08/20 10:07:04', '2020-07-07/08/20 10:07:04', ....
# the update to my answer:
newTimes = []
for date_time_str in formattedTime:
newTimes.append(datetime.datetime.strptime(date_time_str, '%Y-%m-%d %H:%M:%S'))
print(newTimes) # '%Y-%m-%d %H:%M:%S' [datetime.datetime(2020, 7, 8, 18, 56, 47), datetime.datetime(2020, 7, 8, 18, 56, 47), datetime.datetime(2020, 7, 8, 18, 56, 47),...]
Let me know if you have more questions.
I am also attaching this article for datetime which I found really helpful.
Here is the example in repl

Convert datetime to UTC

I have a date string like - 2015-01-05T10:30:47-0800,
It looks to me that this is some timezone because of the offset. How can I get a date string which is in the UTC timezone from the above date string.
I tried the following -
datestring = '2015-01-05T10:30:47-0800'
from dateutil import parser
d = parser.parse(datestring) # datetime.datetime(2015, 1, 5, 10, 30, 47, tzinfo=tzoffset(None, -28800))
import pytz
d.astimezone(pytz.timezone('UTC')) # datetime.datetime(2015, 1, 5, 18, 30, 47, tzinfo=<UTC>)
EDIT -
The above code returns the correct answer. My bad!
Try this:
>>> import dateutil.parser
>>> d = dateutil.parser.parse('2015-01-05T10:30:47-0800')
>>> d.astimezone(dateutil.tz.tzutc())
datetime.datetime(2015, 1, 5, 18, 30, 47, tzinfo=tzutc())

Generating recurring dates using python?

How can I generate recurring dates using Python? For example I want to generate recurring date for "Third Friday of every second month". I want to generate recurring dates for daily, weekly, monthly, yearly (i.e., same as the recurrence function in Outlook Express).
import dateutil.rrule as dr
import dateutil.parser as dp
import dateutil.relativedelta as drel
start=dp.parse("19/02/2010") # Third Friday in Feb 2010
This generates the third Friday of every month
rr = dr.rrule(dr.MONTHLY,byweekday=drel.FR(3),dtstart=start, count=10)
This prints every third Friday:
print map(str,rr)
# ['2010-02-19 00:00:00', '2010-03-19 00:00:00', '2010-04-16 00:00:00', '2010-05-21 00:00:00', '2010-06-18 00:00:00', '2010-07-16 00:00:00', '2010-08-20 00:00:00', '2010-09-17 00:00:00', '2010-10-15 00:00:00', '2010-11-19 00:00:00']
rr is an iterable, so you can use slicing notation to pick out every other item. This prints the third Friday of every other month:
print map(str,rr[::2])
# ['2010-02-19 00:00:00', '2010-04-16 00:00:00', '2010-06-18 00:00:00', '2010-08-20 00:00:00', '2010-10-15 00:00:00']
Above, I used str to prettify the output a little bit. For more flexible string formatting of dates, use strftime: See http://au2.php.net/strftime or the man page for strftime for all the options.
print [d.strftime('%d/%m/%Y') for d in rr[::2]]
# ['19/02/2010', '16/04/2010', '18/06/2010', '20/08/2010', '15/10/2010']
You can give dateutil a try - especially its relativedelta and rrule fetures.
you may try to write this yourself. you will first need an iterator which generates dates separated by a given interval:
import datetime
def dateiter(start, resolution):
date = start
while True:
yield date
date += resolution
now, you can generate dates and filter them:
# generate a list of every tuesday of february
# this iterates over every day from now, and filtered according to the rules
# warning: infinite generator below, there is nothing to end the iteration
tuesdays_of_february = (date for date in dateiter(datetime.datetime.now(), datetime.timedelta(days=1)) if date.weekday() == 4 and date.month == 2)
you can call the iterator yourself until you have enough dates:
>>> next(tuesdays_of_february)
datetime.datetime(2010, 2, 19, 14, 25, 46, 171000)
now, you need to limit the results:
>>> from itertools import *
>>>
>>> # get the five next valid dates:
>>> list(islice(tuesdays_of_february),5)
[datetime.datetime(2010, 2,26, 14, 25, 46, 171000), datetime.datetime(2011, 2, 4
, 14, 25, 46, 171000), datetime.datetime(2011, 2, 11, 14, 25, 46, 171000), datet
ime.datetime(2011, 2, 18, 1 4, 25, 46, 171000), datetime.datetime(2011, 2, 25
, 14, 25, 46, 171000)]
>>>
>>> # or until a condition is met:
>>> list(takewhile( lambda date: date.year < 2014, tuesdays_of_february ))
[datetime.datetime(2012, 2, 3, 14, 25, 46, 171000), datetime.datetime(2012, 2, 1
0, 14, 25, 46, 171000), datetime.datetime(2012, 2, 17, 14, 25, 46, 171000), date
time.datetime(2012, 2, 24, 14, 25, 46, 171000), datetime.datetime(2013, 2, 1, 14
, 25, 46, 171000), datetime.datetime(2013, 2, 8, 14, 25, 46, 171000), datetime.d
atetime(2013, 2, 15, 14, 25, 46, 171000), datetime.datetime(2013, 2, 22, 14, 25,
46, 171000)]
don't forget to have a look at the documentation for the datetime module.

Datetime - 10 Hours

Consider:
now = datetime.datetime.now()
now
datetime.datetime(2009, 11, 6, 16, 6, 42, 812098)
How would I create a new datetime object (past) and minus n values from the hours?
Use timedelta in the datetime module:
import datetime
now = datetime.datetime.now()
past = now - datetime.timedelta(hours=10)
Use a timedelta object.
>>> now = datetime.datetime.now()
>>> now
datetime.datetime(2009, 11, 6, 16, 35, 50, 593000)
>>> ten_hours = datetime.timedelta(hours=10)
>>> now + ten_hours
datetime.datetime(2009, 11, 7, 2, 35, 50, 593000)
>>> now - ten_hours
datetime.datetime(2009, 11, 6, 6, 35, 50, 593000)
Use a timedelta object.
from datetime import datetime
back = datetime.now() - timedelta(hours=10)

Categories

Resources