working on it ...

Filters

Explore Public Snippets

Sort by

Found 992 snippets matching: timestamp

    public by ejmurray modified Jan 22, 2016  249579  16  3  0

    Photo management script. This script will copy photos from "~/Pictures/iPhone Incoming" into a tree the script creates, with folders representing month and years, and photo names timestamped. Completely based on the work of the amazing Dr. Drang; se...

    Photo management script. This script will copy photos from "~/Pictures/iPhone Incoming" into a tree the script creates, with folders representing month and years, and photo names timestamped. Completely based on the work of the amazing Dr. Drang; see here: http://www.leancrew.com/all-this/2013/10/photo-management-via-the-finder/ You can see mor
    #!/usr/bin/python
    
    import sys
    import os, shutil
    import subprocess
    import os.path
    from datetime import datetime
    
    ######################## Functions #########################
    
    def photoDate(f):
      "Return the date/time on which the given photo was taken."
    
      cDate = subprocess.check_output(['sips', '-g', 'creation', f])
      cDate = cDate.split('\n')[1].lstrip().split(': ')[1]
      return datetime.strptime(cDate, "%Y:%m:%d %H:%M:%S")
    
    
    ###################### Main program ########################
    
    # Where the photos are and where they're going.
    sourceDir = os.environ['HOME'] + '/Pictures/iPhone Incoming'
    destDir = os.environ['HOME'] + '/Pictures/iPhone'
    errorDir = destDir + '/Unsorted/'
    
    # The format for the new file names.
    fmt = "%Y-%m-%d %H-%M-%S"
    
    # The problem files.
    problems = []
    
    # Get all the JPEGs in the source folder.
    photos = os.listdir(sourceDir)
    photos = [ x for x in photos if x[-4:] == '.jpg' or x[-4:] == '.JPG' ]
    
    # Prepare to output as processing occurs
    lastMonth = 0
    lastYear = 0
    
    # Create the destination folder if necessary
    if not os.path.exists(destDir):
      os.makedirs(destDir)
    if not os.path.exists(errorDir):
      os.makedirs(errorDir)
    
    # Copy photos into year and month subfolders. Name the copies according to
    # their timestamps. If more than one photo has the same timestamp, add
    # suffixes 'a', 'b', etc. to the names. 
    for photo in photos:
      # print "Processing %s..." % photo
      original = sourceDir + '/' + photo
      suffix = 'a'
      try:
        pDate = photoDate(original)
        yr = pDate.year
        mo = pDate.month
    
        if not lastYear == yr or not lastMonth == mo:
          sys.stdout.write('\nProcessing %04d-%02d...' % (yr, mo))
          lastMonth = mo
          lastYear = yr
        else:
          sys.stdout.write('.')
        
        newname = pDate.strftime(fmt)
        thisDestDir = destDir + '/%04d/%02d' % (yr, mo)
        if not os.path.exists(thisDestDir):
          os.makedirs(thisDestDir)
    
        duplicate = thisDestDir + '/%s.jpg' % (newname)
        while os.path.exists(duplicate):
          newname = pDate.strftime(fmt) + suffix
          duplicate = destDir + '/%04d/%02d/%s.jpg' % (yr, mo, newname)
          suffix = chr(ord(suffix) + 1)
        shutil.copy2(original, duplicate)
      except Exception:
        shutil.copy2(original, errorDir + photo)
        problems.append(photo)
      except:
        sys.exit("Execution stopped.")
    
    # Report the problem files, if any.
    if len(problems) > 0:
      print "\nProblem files:"
      print "\n".join(problems)
      print "These can be found in: %s" % errorDir
    
    
    

    public by atucom modified Feb 1, 2016  192587  0  3  0

    automatically log speedtest results to file with timestamp for logging.

    automatically log speedtest results to file with timestamp for logging.: lolbandwidth.py
    #!/usr/bin/python
    #stolen and modified from the reddit post about the raspbeery pi tweeting at comcast
    #run this every 10 minutes (or w/e) with cron:
    #"crontab -e"
    #*/10 * * * * /home/pi/lolbandwidth.py
    import os
    import sys
    import csv
    import datetime
    import time
    
    def test():
            #run speedtest-cli
            print 'running test'
            #install with "pip install speedtest-cli"
            csvlog = '/home/pi/speed_data.csv'
            a = os.popen("speedtest-cli --simple").read()
            print 'ran'
            #split the 3 line result (ping,down,up)
            lines = a.split('\n')
            print a
            ts = time.time()
            date =datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')
            #if speedtest could not connect set the speeds to 0
            if "Cannot" in a:
                    p = 100
                    d = 0
                    u = 0
            #extract the values for ping down and up values
            else:
                    p = lines[0][6:11]
                    d = lines[1][10:14]
                    u = lines[2][8:12]
            print date,p, d, u
            #save the data to file for local network plotting
            out_file = open(csvlog, 'a')
            writer = csv.writer(out_file)
            writer.writerow((ts*1000,p,d,u))
            out_file.close()
            return
            
    if __name__ == '__main__':
            test()
            print 'completed'
    
    
    

    public by sTiLL-iLL @ SniPitz-KND modified Nov 5, 2014  2416  1  7  19

    nEaTo! timestamp utility - type funktion

    its as tight as I could get it!
    
    // fancy-ish timestamp(ish) function
    
    function getNow() {
    			var months=['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
    			function pad(n) {
    				return (n<10)?'0'+n.toString(10):n.toString(10);
    			}
    			
    			function timestamp() {
    				var d=new Date();
    				return [
    				  d.getDate(),
    				  months[d.getMonth()]
    				  , [pad(d.getHours())
    				  , pad(d.getMinutes())
    				  , pad(d.getSeconds())
    				  , (d.getTime()+"")
    					  .substr(-4, 4)
    				  ].join(':')
    				].join(' ');
    			}
    			return timestamp();
    		}
    		
    		
    		
    		

    public by fadzly modified Nov 1, 2016  4032  0  5  0

    Get magento locale date/time from GMT timestamp / current time

    Get magento locale date/time from GMT timestamp / current time
    date("d-m-Y H:i:s", Mage::getModel('core/date')->timestamp(time()))

    public by maholtz modified Jul 10, 2014  3267  0  6  3

    Alle Datensätze der letzten Monate

    Das Skript liest aus einer Tabelle alle Datensätze der letzten 18 Monate, so dass pro Benutzer der letzte Login zu sehen ist. Als letzte Spalte wird der Timestamp noch einmal ausgegeben.
    SELECT count(*)
         ,max([oid])
        ,min([timestamp])
        ,[benutzer]
        ,MAX(DATEADD(month, -18, SYSDATETIME()))
    FROM [datenbank].[dbo].[tabelle]
    WHERE
      timestamp > DATEADD(month, -18, SYSDATETIME())
      AND benutzer IS NOT NULL
    GROUP BY benutzer
    
    

    public by Fabax modified Aug 30, 2013  1528  0  4  0

    return today's midnight timestamp

    return today's midnight timestamp: get midnight
    function getMidnight(){
      $date = new DateTime();
    	$hours =  $date->format('H');
    	$minutes =  $date->format('i');
    	$seconds =  $date->format('s');
    
    	$hours = ($hours*60)*60;
    	$minutes  = $minutes*60;
    	$midnight = time()-($hours+$minutes+$seconds);
    	$midnight = $date = date('Y-m-d H-i-s', $midnight);
    
    	return $midnight;
    }
    
    

    public by msdn modified Jan 12, 2015  771  0  5  0

    TimestampToString: Converts a SQL Server Timestamp column into a string.

    Converts a SQL Server Timestamp column into a string. The timestamp to be converted. The converted timestamp.
    using InstanceFactory.EntityFrameworkRaceCondition.Data.Entity;
    using InstanceFactory.EntityFrameworkRaceCondition.Models;
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Infrastructure;
    using System.Linq;
    using System.Windows.Controls;
    
    #endregion Private Methods
    
    
    #region Private Static Methods
    
    /// <summary>
    /// Converts a SQL Server Timestamp column into a string.
    /// </summary>
    /// <param name="array">The timestamp to be converted.</param>
    /// <returns>The converted timestamp.</returns>
    private static string TimestampToString
      (
      byte[] array
      )
    {
      if (array.Length != 8)
      {
        throw (new ArgumentOutOfRangeException("array", "The length of the array must be 8."));
      }
    
      return (String.Format("0x{0:x2}{1:x2}{2:x2}{3:x2}{4:x2}{5:x2}{6:x2}{7:x2}",
                array[0], array[1], array[2], array[3], array[4], array[5], array[6], array[7]));
    }

    public by msdn modified Jan 12, 2015  1310  9  6  0

    ConvertFromUnixTimestamp: Converts a UNIX timestamp to a DateTime.

    Converts a UNIX timestamp to a DateTime. The timestamp. The timestamp converted to a DateTime.
    using System;
    using System.Collections.Generic;
    using System.Globalization;
    using System.Linq;
    using System.Net;
    using System.Web;
    using System.Xml.Linq;
    using FeedProcessor.Enums;
    using FeedProcessor.FeedItems;
    using FeedProcessor.Net;
    
    #endregion
    
    /// <summary>
    /// Converts a UNIX timestamp to a DateTime.
    /// </summary>
    /// <param name="timestamp">The timestamp.</param>
    /// <returns>The timestamp converted to a DateTime.</returns>
    internal static DateTime ConvertFromUnixTimestamp(double timestamp)
    {
        return new DateTime(1970, 1, 1, 0, 0, 0, 0).AddSeconds(timestamp);
    }

    public by msdn modified Jan 12, 2015  1326  0  5  0

    getTimestamp: Generates a timestamp suitable for the application verifier token.

    Generates a timestamp suitable for the application verifier token.
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Text.RegularExpressions;
    using System.Collections.Specialized;
    using System.Collections;
    using System.Web;
    using System.Web.Configuration;
    using System.Security.Cryptography;
    using System.IO;
    using System.Net;
    using System.Reflection;
    using System.Xml;
    
    /// <summary>
    /// Generates a timestamp suitable for the application
    /// verifier token.
    /// </summary>
    static string getTimestamp()
    {
        DateTime refTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
        TimeSpan ts = DateTime.UtcNow - refTime;
        return ((uint)ts.TotalSeconds).ToString();
    }

    public by msdn modified Jan 12, 2015  923  0  6  0

    GetSnapshotTime: Gets the snapshot timestamp from the response.

    Gets the snapshot timestamp from the response. The web response. The snapshot timestamp.
    /// <summary>
    /// Gets the snapshot timestamp from the response.
    /// </summary>
    /// <param name="response">The web response.</param>
    /// <returns>The snapshot timestamp.</returns>
    [System.Diagnostics.CodeAnalysis.SuppressMessage(
        "Microsoft.Design",
        "CA1011:ConsiderPassingBaseTypesAsParameters",
        Justification = "Storage only supports HTTP")]
    public static string GetSnapshotTime(HttpWebResponse response)
    {
        return response.Headers[Constants.HeaderConstants.SnapshotHeader];
    }
    • Public Snippets
    • Channels Snippets