def shortRelativeStringFromDate(nsdate): """Input: NSDate object Output: unicode object, date and time formatted per system locale. """ df = NSDateFormatter.alloc().init() df.setDateStyle_(kCFDateFormatterShortStyle) df.setTimeStyle_(kCFDateFormatterShortStyle) df.setDoesRelativeDateFormatting_(True) return unicode(df.stringFromDate_(nsdate))
def stringFromDate(nsdate): """Input: NSDate object Output: unicode object, date and time formatted per system locale. """ df = NSDateFormatter.alloc().init() df.setFormatterBehavior_(NSDateFormatterBehavior10_4) df.setDateStyle_(kCFDateFormatterLongStyle) df.setTimeStyle_(kCFDateFormatterShortStyle) return unicode(df.stringForObjectValue_(nsdate))
def main(): # # UNIX command 'date' # if False: pr("UNIX command 'date'") cmd = 'date' r = commands.getoutput(cmd) pr("UNIX date command", r) pr("r.split()[4]", r.split()[4]) # # Python datetime # if False: pr("Python datetime") pr('datetime.datetime.now() ', datetime.datetime.now() ) t = datetime.datetime.now() - datetime.datetime.utcnow() pr("datetime.now() - datetime.utcnow()", t) pr("timedelta(-1, 68399, 999998) == timedelta(-1, 68400, 0)", datetime.timedelta(-1, 68399, 999998) == datetime.timedelta(-1, 68400, 0) ) pr("datetime.timedelta(hours=-5, seconds = -1) < t < datetime.timedelta(hours=-5, seconds = 1)", datetime.timedelta(hours=-5, seconds = -1) < t < datetime.timedelta(hours=-5, seconds = 1)) # print datetime.timedelta(hours=-5, seconds = 0) < t < datetime.timedelta(hours=-5, seconds = 1) #False # print datetime.timedelta(hours=-5, seconds = -1) < t < datetime.timedelta(hours=-5, seconds = 0) #True t2 = datetime.datetime.utcnow() + t pr('strftime("%a %Y.%m.%d %I:%M:%S")', t2.strftime("%a %Y.%m.%d %I:%M:%S") ) d3 = datetime.datetime(2011, 7, 29, 23, 46, 39) pr( 'str(d3)', str(d3) ) prr("_DATETIME_to_python(d3)", _DATETIME_to_python(d3)) # # Cocoa (Foundation) NSDate, NSCalendar, NSDateFormatter, etc. # pr("Cocoa (Foundation) NSDate, etc.") date1 = NSDate.dateWithTimeIntervalSinceReferenceDate_(333675999.713839) date2 = NSDate.dateWithTimeIntervalSinceReferenceDate_(333675999.713839 - 6 * 30 * 24 *60 * 60) date3 = NSDate.distantPast() # dateWithTimeIntervalSinceNow_(0- 6 * 30 * 24 *60 * 60) pr( "date1" , date1) pr( "date2" , date2) pr( "date3" , date3) prr("_DATETIME_to_python(date1)", _DATETIME_to_python(date1)) # pr( "str(date1) ", str(date1) ) currentCalendar = NSCalendar.currentCalendar() # # time zones # def pr_tz(l, tz): s = tz.secondsFromGMT() / (60 * 60) print "%s:\n\n %r (%s) offset %d hours%s\n" % (l,tz.name(), tz.abbreviation(), s , " (**local**)" if "Local Time Zone " in tz.description() else "") # print tz.description() # timeZone_Current = currentCalendar.timeZone() # # pr_tz('timeZone_Local', timeZone_Local) # # # s = timeZone_GMT.secondsFromGMT() / (60 * 60) # # pr("timeZone_GMT", str(timeZone_GMT) + " offset: %d hours" % s ) # pr( "timeZone_Local.isDaylightSavingTime()", timeZone_Local.isDaylightSavingTime() ) # determines whether daylight saving time is currently in effect. # pr( "timeZone_Local.daylightSavingTimeOffset()", timeZone_Local.daylightSavingTimeOffset() ) # determines the current daylight saving time offset. For most time zones this is either zero or one. # pr( "timeZone_Local.nextDaylightSavingTimeTransition()", timeZone_Local.nextDaylightSavingTimeTransition()) # Formatting for Machines: Controlled Environment Needed # # It is a whole other matter if you need to create a date string according to # the specification of a certain file format or API. # In such a case, you usually have to follow a very strict spec to # make sure the other party can read the string you are generating. # By default, NSDateFormatter uses the user’s current calendar and time zone, # which are possibly different from the requirements. # Most file formats and web APIs use the western, Gregorian calendar, # so we need to make sure that our date formatter uses it, too. dateFormatter_Local = NSDateFormatter.alloc().init() dateFormatter_Current = NSDateFormatter.alloc().init() dateFormatter_GMT = NSDateFormatter.alloc().init() dateFormatter_GMT5 = NSDateFormatter.alloc().init() dateFormatter_NY = NSDateFormatter.alloc().init() # dateFormatter_Local.__name__ = 'dateFormatter_Local' formatter_names = [ ] time_zones = [ ('Local' , NSTimeZone.localTimeZone()) , ('Current' , currentCalendar.timeZone()) , ('GMT' , NSTimeZone.timeZoneForSecondsFromGMT_(0)) , ('GMT5' , NSTimeZone.timeZoneForSecondsFromGMT_(-18000)) , ('NY' , NSTimeZone.timeZoneWithName_(u'America/New_York')) , ('System', NSTimeZone. systemTimeZone() ) , ('G' , NSTimeZone.timeZoneWithAbbreviation_(u'GMT')) ] dx = [ {'name' : n , 'tz' : tz, 'df' : NSDateFormatter.alloc().init() } for n, tz in time_zones ] s = [ "%12s: %s" % (x['name'], "%r (%s) %s%s" % tz_pr(x['tz']) ) for x in dx ] print "\n".join(s) print def eq_classes(dx, k): # z = [] d = {} for n, x in enumerate(dx): if x[k] not in d: d[x[k]] = set([ x['name'] ]) for m in range(n): y = dx[m] if x != y and x[k] == y[k]: # z.append((x['name'], y['name'])) if x[k] in d: d[x[k]].add( x['name'] ) # else: # d[x[k]] = set([ x['name'] ]) if y[k] in d: d[y[k]].add( y['name'] ) # else: # d[y[k]] = [ y['name'] ] return d print "eq_classes of dx (under tz):" print eq_classes_dx = eq_classes(dx, 'tz') print "\n".join([ "%20s: %s" % (x.name(), list(eq_classes_dx[x])) for x in eq_classes_dx]) print eq_names = [ list(eq_classes_dx[x])[0] for x in eq_classes_dx ] dx = [ z for z in dx if z['name'] in eq_names ] s = [ "%12s: %s" % (x['name'], "%r (%s) %s%s" % tz_pr(x['tz']) ) for x in dx ] print "\n".join(s) print # print "\n".join([ "%20s: %r" % [k for k in x] for x in dx ]) # format string (formatter) # format_string = "E yyyy'-'MM'-'dd' 'HH':'mm':'ss VVVV" # ==> "AD 2011-07-29 19:46:39 United States (New York)" # format_string = "E yyyy'-'MM'-'dd' 'HH':'mm':'ss VVV" # ==> " 'Fri 2011-07-29 19:46:39 GMT-04:00' format_string = "E yyyy'-'MM'-'dd' 'HH':'mm':'ss z" # ==> 'Fri 2011-07-29 19:46:39 EDT') or 'EST', or 'GMT-04:00' map ( lambda y : NSDateFormatter.setDateFormat_(y, format_string) , [x['df'] for x in dx] ) # locale locale = NSLocale.alloc().initWithLocaleIdentifier_("en_US_POSIX") pr("NSDate.date()", NSDate.date()) map ( lambda y : NSDateFormatter.setLocale_(y, locale) , [x['df'] for x in dx] ) map ( lambda y : NSDateFormatter.setTimeZone_(y[0], y[1]) , [ (x['df'], x['tz']) for x in dx] ) pr('descriptionWithCalendarFormat:timeZone:locale', date1.descriptionWithCalendarFormat_timeZone_locale_( None, None, locale) ) # format_string,NSTimeZone.timeZoneForSecondsFromGMT_(-18000),locale pr('descriptionWithCalendarFormat:timeZone:locale', date1.descriptionWithCalendarFormat_timeZone_locale_( None, NSTimeZone.timeZoneForSecondsFromGMT_(-18000), locale) ) # format_string,NSTimeZone.timeZoneForSecondsFromGMT_(-18000),locale for a in [date1, date2, date3]: dsd = get_datestrings(dx, a) s = [ "%12s: %r" % (x[0], x[1] ) for x in dsd ] print "\n".join(s) print # # date1_components # fcdc = currentCalendar.components_fromDate_( NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit , date1 ) pr( "currentCalendar.components_fromDate", [ fcdc.year(), fcdc.month(), fcdc.day(), fcdc.hour(), fcdc.minute(), fcdc.second(), ] ) dateOfKeynote = currentCalendar.dateFromComponents_(fcdc) pr( "currentCalendar.dateFromComponents", dateOfKeynote )
def get_datestrings(dx, date1): return map ( lambda y : (y[0], NSDateFormatter.stringFromDate_(y[1], date1)) , [ (x['name'] , x['df']) for x in dx] )
from Foundation import NSCalendar, NSDayCalendarUnit, NSWeekdayCalendarUnit,\ NSYearCalendarUnit, NSMonthCalendarUnit, NSHourCalendarUnit, \ NSMinuteCalendarUnit, NSSecondCalendarUnit, NSTimeZone, NSDate, \ NSDateFormatter, NSGregorianCalendar, NSLocale # choose some timezones with which to display some dates, they're fun! time_zones = [ ('Local' , NSTimeZone.localTimeZone()) , ('GMT' , NSTimeZone.timeZoneForSecondsFromGMT_(0)) # ('G' , NSTimeZone.timeZoneWithAbbreviation_(u'GMT')) ] dateFormatters = [ {'name' : n , 'tz' : tz, 'df' : NSDateFormatter.alloc().init() } for n, tz in time_zones ] map ( lambda y : NSDateFormatter.setTimeZone_(y[0], y[1]) , [ (x['df'], x['tz']) for x in dateFormatters] ) format_string = "E yyyy'-'MM'-'dd' 'HH':'mm':'ss z" # ==> 'Fri 2011-07-29 19:46:39 EDT' or 'EST', or 'GMT-04:00' format_string = "E yyyy.MM.dd HH:mm z" # ==> Tue 2012.04.03 00:39 EDT map ( lambda y : NSDateFormatter.setDateFormat_(y, format_string) , [x['df'] for x in dateFormatters] ) def print_timezones(l): print l + ":" # "time_zones:" print s = [ "%12s: %s" % (x['name'], "%r (%s) %s%s" % tz_pr(x['tz']) ) for x in dateFormatters ] print "\n".join(s) print # formatting assist
class Decoy(object): def get(self, url): unsupported = 'could not find the "requests" library (try running "python setup.py build" first)' raise RuntimeError(unsupported) HTTP = Decoy() def binaryish(content, format): bin_types = ('pdf','eps','png','jpg','jpeg','gif','tiff','tif','zip','tar','gz') bin_formats = ('raw','bytes','img','image') if any(b in content for b in bin_types): return True if format: return any(b in format for b in bin_types+bin_formats) return False _nsdf = NSDateFormatter.alloc().init() _nsdf.setLocale_(NSLocale.alloc().initWithLocaleIdentifier_("en_US_POSIX")) _nsdf.setDateFormat_("EEE',' dd' 'MMM' 'yyyy HH':'mm':'ss zzz") _nsdf.setTimeZone_(NSTimeZone.timeZoneForSecondsFromGMT_(0)) def last_modified(resp): """Return the last modified date as a unix time_t""" last_mod = _nsdf.dateFromString_(resp.headers.get('Last-Modified')) if not last_mod: last_mod = NSDate.date() return last_mod.timeIntervalSince1970() ### File/URL Reader ### def read(pth, format=None, encoding=None, cols=None, **kwargs):
from __future__ import with_statement __author__ = "dbr/Ben" __version__ = "1.9" import os import time import errno import httplib import urllib2 import StringIO from hashlib import md5 from threading import RLock from Foundation import NSDateFormatter, NSLocale, NSTimeZone, NSDate _date_parser = NSDateFormatter.alloc().init() _date_parser.setLocale_(NSLocale.alloc().initWithLocaleIdentifier_("en_US_POSIX")) _date_parser.setDateFormat_("EEE',' dd' 'MMM' 'yyyy HH':'mm':'ss zzz") _date_parser.setTimeZone_(NSTimeZone.timeZoneForSecondsFromGMT_(0)) def GET(url): """Return the contents of a url (from cache if possible)""" opener = urllib2.build_opener(CacheHandler("/tmp/plod")) response = opener.open(url) last_mod = _date_parser.dateFromString_(response.headers.get('Last-Modified')) if not last_mod: last_mod = NSDate.date() return response, last_mod.timeIntervalSince1970()
def dateFromString(myDateAsAStringValue): df = NSDateFormatter.alloc().init() df.setTimeStyle_(NSDateFormatterFullStyle) # <=== magic. have to do this(?) df.setDateFormat_("yyyy-MM-dd HH:mm:ss") #"yyyy-MM-dd hh:mm:ss") # "2013-03-30 18:11:07" myDate = db_df.dateFromString_(myDateAsAStringValue) return myDate
from __future__ import with_statement __author__ = "dbr/Ben" __version__ = "1.9" import os import time import errno import httplib import urllib2 import StringIO from hashlib import md5 from threading import RLock from Foundation import NSDateFormatter, NSLocale, NSTimeZone, NSDate _date_parser = NSDateFormatter.alloc().init() _date_parser.setLocale_( NSLocale.alloc().initWithLocaleIdentifier_("en_US_POSIX")) _date_parser.setDateFormat_("EEE',' dd' 'MMM' 'yyyy HH':'mm':'ss zzz") _date_parser.setTimeZone_(NSTimeZone.timeZoneForSecondsFromGMT_(0)) def GET(url): """Return the contents of a url (from cache if possible)""" opener = urllib2.build_opener(CacheHandler("/tmp/plod")) response = opener.open(url) last_mod = _date_parser.dateFromString_( response.headers.get('Last-Modified')) if not last_mod: last_mod = NSDate.date()
def pr7z(self, item_dict, stak=None, depth_limit=None, verbose_level_threshold=1): """0-0 vol0006 5651 6227 Wed 2013.03.20 13:29 EDT 1 <filename>""" if self.verbose_level < verbose_level_threshold: return # from "man ls" # If the -l option is given, the following information is displayed for each file: # file mode, number of links, owner name, group name, number of bytes in the file, # abbreviated month, day-of-month file was last modified, hour file last modified, # minute file last modified, and the pathname. # assemble a list of strings to print, then " ".join() s = [] if GPR.verbose_level >= 2 and 'current_item_directory_is_being_checked' in item_dict: g = "[^]" if item_dict['current_item_directory_is_being_checked'] else "[-]" s += [g] # if RS1_db_rels is not None: # s0 = dict([(k, RS1_db_rels[k]) for k in RS1_db_rels] )# avoid self-creation # s1 = '[%s]' % "-".join([ "%d"%(len(s0[k])) if k in s0 else "*" for k in stak]) # s += [ "%-6s" % s1 ] # # # this line *creates* an entry since RS is a *default* dict and k isn't already present in RS # # s1 = '[%s]' % "-".join(["%d"%(len(RS1_db_rels[k])) for k in stak]) # # if False: # s2 = '[%s]' % "-".join(["%d"%(len(RS2_ins[k])) for k in RS2_ins]) # s1 += '+'+s2 # s += [ "%-12s" % s3 ] if 'vol_id' in item_dict: fmt = "%%-%ds" % self.vol_id_width # "%-7s" s += [ fmt % item_dict['vol_id'] ] if 'NSFileSystemFolderNumber' in item_dict: # really, if is NSDict or relation folder_id = item_dict['NSFileSystemFolderNumber'] else: folder_id = item_dict['folder_id'] file_id = item_dict['NSFileSystemFileNumber'] fmt = "%%%dd %%%dd" % (self.file_id_width , self.file_id_width) s += [ "%8d %8d" % (folder_id, file_id) ] # If the modification time of the file is more than 6 months # in the past or future, then the year of the last modification # is displayed in place of the hour and minute fields. [man ls] file_mod_date = item_dict[NSURLContentModificationDateKey] # compare: # Returns an NSComparisonResult value that indicates the temporal ordering of the receiver and another given date. # date_six_months_ago = NSDate.dateWithTimeIntervalSinceNow_(0- 6 * 30 * 24 *60 * 60) date_six_months_ago = NSDate.dateWithTimeIntervalSinceNow_(0- 12 * 30 * 24 *60 * 60) # one year ago if False: # ie, if doing short versions if date_six_months_ago.compare_(file_mod_date) == NSOrderedDescending: # ie, date_six_months_ago is later in time than file_mod_date format_string = self.date_format_short_early if format_string.endswith(" z"): fmt = "%3s %15s" else: fmt = "%3s %11s" else: format_string = self.date_format_short if format_string.endswith(" z"): fmt = "%3s %15s" else: fmt = "%3s %11s" # don't need to set format string for this formatter? each time through? NSDateFormatter.setDateFormat_(dateFormatters[0]['df'], format_string) sa = dateFormatters[0]['df'].stringFromDate_(file_mod_date) s += [ fmt % ( sa[0:3], sa[4:] ) ] else: # no difference for early or recent for long date format if date_six_months_ago.compare_(file_mod_date) == NSOrderedDescending: format_string = self.date_format_early fmt = "%19s" else: format_string = self.date_format fmt = "%19s" # don't need to set format string for this formatter? each time through? NSDateFormatter.setDateFormat_(dateFormatters[0]['df'], format_string) sa = dateFormatters[0]['df'].stringFromDate_(file_mod_date) s += [ fmt % ( sa, ) ] depth = item_dict['depth'] filename = item_dict[NSURLNameKey] if item_dict['NSURLIsDirectoryKey']: filename += "/" if 'directory_is_up_to_date' in item_dict: filename += ("(up-to-date)" if item_dict['directory_is_up_to_date'] else "(modified)" ) file_uti = item_dict[NSURLLocalizedTypeDescriptionKey] # NSURLTypeIdentifierKey] if len(file_uti) > self.file_uti_width: n1 = int(self.file_uti_width/2) n2 = self.file_uti_width - n1 file_uti = file_uti[:n1] + u"—" + file_uti[-n2:] fmt = "%%-%ds" % ( self.file_uti_width ) s += [ fmt % file_uti ] if depth_limit and depth >= depth_limit-1: s += [ "%2d! %-54s" % (depth, filename) ] else: s += [ "%2d %-54s" % (depth, filename) ] if GPR.verbose_level >= 2: print print " ".join(s) #print repr(s) # " ".join(s) if GPR.verbose_level >= 2: print