0

How in Python (3.4), how can I create a numeric date time representation? It will be used as a 'score' and ZRANGEBYSCORE* query on Redis?

More details: I'm using Redis and Python. I need to represent dates and time as numbers to allow me to query a Sorted Set. The set would be keyed on an ID. The score would be the numeric date time representation.

I've read this is possible using ZRANGEBYSCORE to get article IDs within a date range, but I'm unable to find any examples on how to create a numeric date time representation in Python that I can use as the score! Would you use something like an epoch?

9
  • 2
    Um... like a standard timestamp? Commented Apr 16, 2016 at 22:00
  • @TigerhawkT3 Yes, exactly, but it would need to allow me to for example say, fetch all ids in the last x days etc Commented Apr 16, 2016 at 22:06
  • Say I have a date like 2016-04-15T14:43:44.269Z, I need this to be a numeric representation somehow. This way, I could get all keys within a range etc @TigerhawkT3 Commented Apr 16, 2016 at 22:08
  • If you need numbers (like int or float), that's what timestamps are for. If you want to do calculations, it's much easier with datetime, although that's a full object rather than a single number. Commented Apr 16, 2016 at 22:10
  • @TigerhawkT3 Would you use something like an epoch? Commented Apr 16, 2016 at 22:11

1 Answer 1

3

The time module has a time() function that produces a localized Unix-style timestamp.

>>> import time
>>> int(time.time())
1460845456

Note again that this is localized - it is based on the local time and is not timezone-aware.

If you want to do calculations, the datetime module is very useful:

>>> import datetime
>>> datetime.datetime.now()
datetime.datetime(2016, 4, 16, 15, 26, 14, 657718)
>>> datetime.datetime.now().day
16
>>> datetime.datetime.now() - datetime.timedelta(days=3)
datetime.datetime(2016, 4, 13, 15, 26, 43, 769385)

You can also convert between these formats:

>>> datetime.datetime.fromtimestamp(time.time())
datetime.datetime(2016, 4, 16, 15, 28, 6, 29099)
>>> datetime.datetime.now().timestamp()
1460845739.061133
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.