0

I have two columns in my database named dtp_s and dtp_e. Both of these columns hold strtotime() formatted ints which I then use in my PHP application to calculate hours/minutes between time intervals.

I want to display the 5 most recent records in date order, which works fine when I use this:

SELECT id
FROM _records
ORDER BY dtp_s DESC
LIMIT 5

However, I now want to convert the dtp_s back to a DateTime format in my Query and only pull out the data for that week. The issue I have is the records are for a weekly quota, my idea of pulling 5 records out covers Monday-Fri (which is all that is needed and uploaded) however, the following Monday will show the previous weeks Tuesday, Wednesday, Thursday and Friday as well.

I tried to use date_sub for a one week interval but this seems to only work on DateTime datatype columns, not a Unix timestamp:

SELECT id
FROM _records
WHERE dtp_s > DATE_SUB(NOW(), INTERVAL 1 WEEK);
ORDER BY dtp_s DESC
LIMIT 5

How only select the data that is from the current week by converting my formatted DateTime back to DateTime format? I appreciate any help in advance.

An example of my dtp_s and dtp_e is: 1595570400 1595584800

GMB
  • 216,147
  • 25
  • 84
  • 135
Jaquarh
  • 6,493
  • 7
  • 34
  • 86

2 Answers2

1

You can convert the filter value to a unix timestamp with date function unixtimestamp(), like so:

where dtp_s > unix_timestamp(now() - interval 1 week)
GMB
  • 216,147
  • 25
  • 84
  • 135
  • 1
    I Googled if there was a Unix timestamp conversion about 50 times and was just hit with posts like [this](https://stackoverflow.com/questions/2904256/how-can-i-convert-bigint-unix-timestamp-to-datetime-in-sql-server) - Thank you so much! I'll mark this when I can - it worked perfectly. – Jaquarh Jul 24 '20 at 23:41
1

Actually, you can directly use unix_timestamp() with no conversion:

where dtp_s > unix_timestamp() - 7 * 24 * 60 * 60

Although unix_timestamp() can be very useful, unix_timestamp(now()) is actually redundant. You can just do the whole calculation in the domain of unix timestamps.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786