Regex - Slice Date - Aug 22, 2017 02:00 PM EDT - regex

I'm trying to take a date, for example Aug 22, 2017 02:00 PM EDT
and get the month, day, year from it.
month = re.findall(r'', date)[0]
day = re.findall(r'', date)[0]
year = re.findall(r'', date)[0]
I've started with something like this:
(.*)(?<=[a-zA-Z]{3}\s)
for the month. Is there a better way to do this?

You need to first convert to datetime and then extract the needed values like this (reusing the example):
from datetime import datetime
datetime_object = datetime.strptime('Jun 1 2005 1:33PM', '%b %d %Y %I:%M%p')
print(datetime_object.year, datetime_object.month, datetime_object.day)
From what I can see you probably won't need to specify the format but pass the string directly to the datetime.strptime function.

Related

Read Javascript date input in Django

I have a calendar/datepicker done in Javascript that creates an input of the following format "Thu Mar 29 2018"
On submit, I want to read the date in a Django date field, but it fails.
What solutions do I have ?
Use datetime.strptime
In your case
from datetime import datetime
datetime_format = "%a %b %d %Y"
date_object = datetime.strptime("Thu Mar 29 2018", datetime_format)

How to print the current time in the format Day, Date Month Year HH:MM:SS?

How to print the current time in the format Day, Date Month Year HH:MM:SS
Mon, 28 Aug 2017 15:37:01 .
And then, convert this timestamp to epoch seconds & vice-versa.
datetime module does all the job
>>> import datetime
>>> datetime.datetime.now().strftime("%a, %d %B %Y %H:%M:%S")
'Tue, 29 August 2017 03:04:21'

How can I correctly convert this?

I tried a couple of times converting this date format
Wed, 02 April 2015 15:50:53 SAST
to this format
YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ]
but with no luck so far.
Is there any better way to this, that I might have missed?
Here's what I attempted:
date = Wed, 02 April 2015 15:50:53 SAST
splitter = date.split(" ")
joiner = " ".join(splitter[1:len(splitter)-1])
date = datetime.datetime.strptime(joiner,"%d %b %Y %H:%M:%S")
date = datetime.datetime.strftime(date,"%A, %b %d %Y %H:%M:%S %z")
When I'm saving it to the db, I'm receiving this error:
[Wed, 02 April 2015 15:50:53 SAST for that value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format."]
Have a look at strptime (str --> time) and strftime (date --> str).
EDIT:
You are trying to save a string to a DateTimeField. Just remove the string conversion (strftime).

Finding difference between string time objects in python

I have a list of strings that I am reading from a file - Each of the strings has a time offset that was recorded while storing the data.
date1= "Mon May 05 20:00:00 EDT 2014"
date2="Mon Nov 18 19:00:00 EST 2013"
date3="Mon Nov 07 19:00:00 PST 2013"
I need to find the difference in days between each pair of strings.
from datetime import datetime
from dateutil import tz
def days_hours_minutes(td):
return td.days, td.seconds//3600, (td.seconds//60)%60
date1='Fri Dec 05 19:00:00 2014' # it does not work with EDT, EST etc.
date2='Fri Dec 03 19:00:00 2014'
fmt = "%a %b %d %H:%M:%S %Y"
str1 = datetime.strptime(date1, fmt)
str2 = datetime.strptime(date2, fmt)
td=(str1-str2)
x=days_hours_minutes(td)
print x
#gives (2, 0, 0)
Basically, convert each string to its "my_time_obj" and then take the difference in days.
However, my actual string dates, have "EDT", "EST", "IST" etc - and on using the %Z notation, I get the ValueError: time data 'Fri Dec 05 19:00:00 EST 2014' does not match format '%a %b %d %H:%M:%S %Z %Y'
from the datetime documentation, I see that I can use %Z to convert this to a timezone notation - what am I missing ?
https://docs.python.org/2/library/datetime.html
I would go with parsing the timezone using pytz and do something like this (given that you know how your date string is built):
from datetime import datetime
from dateutil import tz
from pytz import timezone
def days_hours_minutes(td):
return td.days, td.seconds//3600, (td.seconds//60)%60
date1_str ='Fri Dec 05 19:00:00 2014 EST'
date2_str ='Fri Dec 03 19:00:00 2014 UTC'
fmt = "%a %b %d %H:%M:%S %Y"
date1_list = date1_str.split(' ')
date2_list = date1_str.split(' ')
date1_tz = timezone(date1_list[-1]) # get only the timezone without date parts for date 1
date2_tz = timezone(date2_list[-1]) # get only the timezone without date parts for date 2
date1 = date1_tz.localize(datetime.strptime(' '.join(date1_list[:-1]), fmt)) # get only the date parts without timezone for date 1
date2 = date2_tz.localize(datetime.strptime(' '.join(date2_list[:-1]), fmt)) # get only the date parts without timezone for date 2
td=(date1-date2)
x=days_hours_minutes(td)
print x
Converting time strings to POSIX timestamps and finding the differences using only stdlib:
#!/usr/bin/env python
from datetime import timedelta
from email.utils import parsedate_tz, mktime_tz
dates = [
"Mon May 05 20:00:00 EDT 2014",
"Mon Nov 18 19:00:00 EST 2013",
"Mon Nov 07 19:00:00 PST 2013",
]
ts = [mktime_tz(parsedate_tz(s)) for s in dates] # timestamps
differences = [timedelta(seconds=a - b) for a, b in zip(ts, ts[1:])]
print("\n".join(map(str, differences)))
Read the above links about the inherit ambiguity of the input. If you want a more robust solution; you have to use explicit pytz timezones such as 'America/New_York' or else email module hardcodes "timezone abbr. to utc offset" mapping e.g., EDT -> -0400, EST -> -0500, PST -> -0800.
Output
168 days, 0:00:00
10 days, 21:00:00
differences is a list of timedelta objects, you could get full days using td.days attribute (for non-negative intervals) or to get the value including fractions:
days = td.total_seconds() / 86400

RubyMotion Day Number of year for today

I want to generate the current day number using RubyMotion code. I have looked at several IOS solutions but I'm not experienced enough to translate the code successfully to RubyMotion.
I am currently at the following point:
def today
NSDate.today
end
def day_number
NSDate.from_components (day: today)
end
When I run the above it gives me an return of 3852055-06-16 00:00:00 +0100. I thought that the 3852055 part was seconds but it doesn't seem to equate to either todays date or to 16th of June - and in any case why should it be returning 06-16 instead of 02-08?? Totally confused here.
I just want to get todays day number. As I write the date is 2nd August 2014 and the day number should be 214 so I'm obviously way out somewhere.
Any help would be greatly appreciated.
cheers
This will do the trick:
daynum = NSCalendar.currentCalendar.ordinalityOfUnit(NSDayCalendarUnit, inUnit:NSYearCalendarUnit, forDate:NSDate.date)
Now suppose you have the date in the form of a string, and you want to get the day number for it:
datestr = "2014-01-01 11:08:56 +0000"
First create an NSDateFormatter to convert the String into an NSDate
df = NSDateFormatter.new
df.dateFormat = "yyyy-MM-dd HH:mm:ss z"
mydate = df.dateFromString(datestr)
daynum = NSCalendar.currentCalendar.ordinalityOfUnit(NSDayCalendarUnit, inUnit:NSYearCalendarUnit, forDate:mydate)
If your date string is simpler:
datestr = "2014-01-01"
just use a simpler dateFormat string:
df.dateFormat = "yyyy-MM-dd"
I suggest you to take a look at motion-support gem and especially at core-exttime.
You can play with dates as you want:
=> Mon, 04 Aug 2014
(main)> Time
=> Time
(main)> Time.today
=> 2014-08-04 00:00:00 +0200
(main)> Date.today.day
=> 4
(main)> Time.today.day
=> 4
and a lot more.