How to generate a fixed-length hash based on current date and time in Python?

后端 未结 5 599
旧巷少年郎
旧巷少年郎 2021-02-02 17:46

I want to generate a fixed-length (say 10 characters) hash based on current date & time. This hash will be append to names of the uploaded files from my users. How can I do

相关标签:
5条回答
  • 2021-02-02 17:52

    Batteries included:

    import hashlib
    import time
    
    hash = hashlib.sha1()
    hash.update(str(time.time()))
    print hash.hexdigest()
    print hash.hexdigest()[:10]
    
    0 讨论(0)
  • 2021-02-02 17:55

    What about changing the base of current milliseconds since epoch. For example, in JavaScript, changing to base 36:

    Date.now().toString(36)
    

    Results in :

    "jv8pvlbg"
    

    That should be a safe hash, up to milliseconds, respect date order and smaller than 10.

    The only thing is that is not safe, but in your case security is not important right?

    Sorry I don't have the answer for python, but it should by straightforward and should nor require any library. My two cents.

    0 讨论(0)
  • 2021-02-02 18:11

    Check out strftime for python. You can format the date/time string any number of ways to get the 'look' you want.

    0 讨论(0)
  • 2021-02-02 18:12

    I think my comment is a reasonable answer so I am going to post it. The code uses the python time() function to get the number of seconds since the unix epoch:

    import time
    import datetime
    ts = int(time.time())  # this removes the decimals
    
    # convert the timestamp to a datetime object if you want to extract the date
    d = datetime.datetime.fromtimestamp(ts)
    

    The time stamp is currently a 10 digit integer that can easily be converted back to a datetime object for other uses. If you want to further shrink the length of the timestamp you could encode the number in hexadecimal or some other format. ie.

    hex(int(time.time()))
    

    This reduces the length to 8 characters if you remove the 0x prefix

    EDIT:

    In your comment you specified that you don't want people to figure out the original date so I would suggest doing something like:

    hex(int(time.time() + 12345))[2:]   #The [2:] removes the 0x prefix
    

    Just chose a number and remember to subtract it when you are trying to extract the timestamp. Without knowing this number the user would have a very difficult time inferring the real date from your code.

    int(stamp,16) - 12345  
    
    0 讨论(0)
  • 2021-02-02 18:15
    import time
    '{0:010x}'.format(int(time.time() * 256))[:10]
    
    0 讨论(0)
提交回复
热议问题