7
\$\begingroup\$

In this challenge you have to find out which nth second it is now in this year, current date and time now. Or in other words, how many seconds have passed since New Year.

An example current Date is (it's not given, you'll have to find the current Date):

March 5, 2021 1:42:44 AM

For which the answer is 5449364 (or optionally 5449365 if you count January 1, 2021 0:00:00 as the first second).

So you should return or output which 'th second it is now in this year. Standard loopholes apply, shortest code wins. You may keep fractional seconds in output optionally.

\$\endgroup\$
7
  • 7
    \$\begingroup\$ And for your example date what is the expected output? \$\endgroup\$
    – manatwork
    Mar 5 '21 at 6:11
  • 4
    \$\begingroup\$ What do you mean by "th"? \$\endgroup\$
    – pxeger
    Mar 5 '21 at 8:16
  • 2
    \$\begingroup\$ @pxeger I guess the title should read "Which -th second now in this year", so that the expected answer is something like "it is 1234567th second". Maybe it's better to say "how may seconds have passed in this year". \$\endgroup\$
    – Bubbler
    Mar 5 '21 at 8:21
  • 4
    \$\begingroup\$ For Jan 01 2020 00:00:00, should I output 1 or 0? Also, do you prefer time in UTC, or in user's time zone, or both OK? \$\endgroup\$
    – tsh
    Mar 5 '21 at 9:06
  • 1
    \$\begingroup\$ This still doesn't address time zones at all. \$\endgroup\$
    – Wheat Wizard
    Mar 6 '21 at 0:23

25 Answers 25

6
\$\begingroup\$

PHP, 27 bytes

<?=time()-strtotime('1/1');

time()           // current timestamp in seconds
strtotime('1/1') // timestamp of January 1st

Try it online!

\$\endgroup\$
0
5
\$\begingroup\$

Python 2, 55 bytes

from time import*
k=86400
print~-gmtime()[7]*k+time()%k

Try it online!

-4 bytes thanks to Wasif

-11 bytes thanks to dingledooper

\$\endgroup\$
5
  • \$\begingroup\$ 64 bytes switch to python 2 and keeping fractional output is allowed \$\endgroup\$
    – wasif
    Mar 5 '21 at 6:13
  • \$\begingroup\$ 60 bytes \$\endgroup\$ Mar 5 '21 at 6:37
  • \$\begingroup\$ And another 5 bytes can be saved since the attribute can somehow be indexed. \$\endgroup\$ Mar 5 '21 at 9:10
  • \$\begingroup\$ I realized this is similar to the AWK verison I did... I think you need to -k on the end since the tm_yday field in the gmtime() call includes the current day. Meaning on Jan 1st, the tm_yday is 1 not 0. So you'll get an extra day's worth of seconds. \$\endgroup\$
    – cnamejj
    Mar 6 '21 at 3:15
  • 3
    \$\begingroup\$ @cnamejj the "~-" before the gmtime() does exactly that :) \$\endgroup\$ Mar 6 '21 at 7:00
3
\$\begingroup\$

PowerShell, 31 bytes

new-timespan 1/1 (date)|% t*ls*

Try it online!

Too late to post this one


PowerShell, 71 bytes

$x=date;((($x|% d*r)-1)*86400)+($x.hour*3600)+($x.minute*60)+($x|% s*d)

Try it online!

Example output:

Friday, March 5, 2021 6:20:21 AM
5466021

You just multiply day of year by 86400 (246060) and then minutes by 60, hours by 3600 (60*60) and seconds, and sum up all

\$\endgroup\$
2
  • \$\begingroup\$ Just realized that you need to multiply (day of year - 1) by 86400 and not day of year since the count starts from 1. \$\endgroup\$ Mar 5 '21 at 6:18
  • \$\begingroup\$ @ManishKundu thanks for the fix \$\endgroup\$
    – wasif
    Mar 5 '21 at 6:21
3
\$\begingroup\$

R, 73 bytes

`?`=as.double
-?as.POSIXct(paste0(substr(t<-Sys.time(),1,4),"-01-01"))-?t

Try it online!

Returns the index of the current second, in the year that the program is run (currently 2021 at time of posting).

The POSIXct class used by R to represent dates conveniently equals the number of seconds since the start of 1970.
So, to calculate the index of the current second this year (2021), we just need to subtract the number of seconds between 1 Jan 1970 and 1 Jan 2021, which is 1609455600. This requires only 32 bytes of code.

Unfortunately, all of the slickness of the approach above is somewhat lost by the clunkiness of extracting a string to represent 1 Jan of the current year...

\$\endgroup\$
2
\$\begingroup\$

Red, 58 bytes

d: now prin d/11 - 1 * 86400 +(d/7 * 3600)+(d/8 * 60)+ d/9

Try it online!

Explanation: d is of date! datatype. I would normally acces its fields usng path notation like d/yearday to find which date of the year is today. Luckily Red has ordinal accessors for the fields as follows:

Index Name
1     date
2     year
3     month
4     day
5     zone
6     time
7     hour
8     minute
9     second
10    weekday
11    yearday
12    timezone
13    week
14    isoweek
\$\endgroup\$
2
\$\begingroup\$

JavaScript (V8), 53 bytes

print(((n=new Date)-new Date(n.getFullYear(),0))/1e3)

Try it online!

Prints fractional number of seconds. Adding |0 will make this an integer for 2 more bytes.

\$\endgroup\$
2
\$\begingroup\$

Excel, 20 or 36 bytes

This works for just 2021

=(NOW()-44197)*86400

This works for all years.

=(NOW()-DATE(YEAR(NOW()),1,1))*86400
\$\endgroup\$
3
  • 2
    \$\begingroup\$ Will this still work in 2022? \$\endgroup\$ Mar 9 '21 at 4:55
  • \$\begingroup\$ It will not. I suppose I was interpreting this year to mean 2021. \$\endgroup\$
    – Axuary
    Mar 9 '21 at 14:31
  • \$\begingroup\$ (that's what I did, initially, but then realised that everyone else interpreted it as 'current year' and so I followed the herd... posting 2 versions like you've done now seems the best option!) \$\endgroup\$ Mar 9 '21 at 14:47
2
\$\begingroup\$

JavaScript (V8), 46 32 bytes

-14 bytes thanks to ophact!

_=>(Date.now()-16094592e5)/1e3|0

Try it online!

The function gets the timestamp of the current time, i.e. number of milliseconds from the 1st January 1970

new Date().getTime()

Then subtract the number of milliseconds passed from 1970 to 2021

1609459200000

And divides the result by 1000 to get the number of seconds.

Finally it returns the result after having converted it to unsigned integer through the bitwise OR | (because the division gives a floating point number)

The variable _ is never used but passing no argument would cost one byte ()=>.

\$\endgroup\$
4
  • 1
    \$\begingroup\$ 16094592e5 and 1e3 as opposed to their full length counterparts seems to save a few bytes \$\endgroup\$
    – user100690
    May 7 '21 at 17:20
  • \$\begingroup\$ @ophact you are right thanks! I've never considered to use this notation before. \$\endgroup\$ May 8 '21 at 11:02
  • 1
    \$\begingroup\$ Also save more bytes with Date.now() instead of new Date().getTime() \$\endgroup\$
    – user100690
    May 8 '21 at 11:32
  • \$\begingroup\$ @ophact wow that's nice to know! Thanks again! \$\endgroup\$ May 8 '21 at 16:48
2
\$\begingroup\$

Japt, 19 12 11 bytes

K-ÐKi T)zA³

Try it online!

does current time(in ms) - january 1 , divide by 1000 and floor.

-7 bytes from Shaggy and AZTECC0.

-1 byte from Shaggy.

\$\endgroup\$
3
  • 1
    \$\begingroup\$ N.z returns floored division for 16 \$\endgroup\$
    – AZTECCO
    Mar 5 '21 at 7:51
  • \$\begingroup\$ 12 bytes \$\endgroup\$
    – Shaggy
    Mar 5 '21 at 8:26
  • \$\begingroup\$ 11 bytes \$\endgroup\$
    – Shaggy
    May 10 '21 at 15:48
1
\$\begingroup\$

Javascript (Browser), 163 bytes

d=new Date();x=d.getFullYear();y=((Date.UTC(x,d.getMonth(),d.getDate())-Date.UTC(x,0,0))/864e5)-1;alert(y*86400+d.getHours()*3600+d.getMinutes()*60+d.getSeconds())

UTC based day of year calculation thanks to this answer in Stack Overflow, I then tried to golf and use the function

JavaScript (V8), 163 bytes

d=new Date();x=d.getFullYear();y=((Date.UTC(x,d.getMonth(),d.getDate())-Date.UTC(x,0,0))/864e5)-1;print(y*86400+d.getHours()*3600+d.getMinutes()*60+d.getSeconds())

Try it online!

\$\endgroup\$
1
\$\begingroup\$

T-SQL 55 Bytes,

PRINT DATEDIFF(S,STR(YEAR(GETDATE()))+'0101',GETDATE())

DATEDIFF takes difference between two DATETIME types, S makes the difference be in seconds.

GETDATE() gets the local datetime as a DATETIME.

YEAR takes a DATETIME/DATE argument, returns the year component of the argument.

STR converts the YEAR integer to a string. + is also string concatenation in T-SQL.

The string in format 'YYYYMMDD' is implicitly converted to a DATETIME with a zero time component in the DATEDIFF function.

Results in the number of seconds since the 1st of Jan this Year.

\$\endgroup\$
0
1
\$\begingroup\$

AWK, 47 bytes

$0=strftime("%j",r=systime(),1)*(q=86400)+r%q-q

Try it online!

I wasn't sure if the seconds into the year should start from midnight Jan 1 in the local timezone or in UTC. This version works for UTC.

It figures out the julian date (the number of days into the year), converts that to seconds then adds in the fractional day's worth of seconds.

strftime("%j",r=systime(),1)

Gets the julian date, and stores the UNIX epoch in variable r in the process. It add a 3rd parameter on strftime to get the time in UTC.

*(q=86400)

Converts the days to seconds and saves the constant "seconds per day" in for use later.

+r%q

Adds in the seconds corresponding to the HH:MM:SS offset from midnight UTC using modulo math.

-q

And this is annoying 2 characters I couldn't figure out how to drop... Since julian days start with 1, the %j include the current day so we have to subtract a full day.

$0=

Finally, assigning the result to $0 means the whole expression is actually a condition, which is always truthy except for at exactly midnight on Jan 1st, so the value is printed.

If an offset in seconds from local time is acceptable, this more straightforward, and slightly shorter code would work.

$0=systime()-mktime(strftime("%Y 1 1 0 0 0"))

That one just subtracts the UNIX epoch for Jan 1st at mightnight of the current year from the current epoch time.

\$\endgroup\$
1
\$\begingroup\$

Python 2, 79 bytes

from datetime import*
print (datetime.now()-datetime(2021,1,1)).total_seconds()

Try it online!


Python 2, 105 bytes

from datetime import*
n=datetime.now();print n.timetuple().tm_yday*86400+n.hour*3600+n.minute*60+n.second

Try it online!

Equal-byte alternative:

Python 2, 105 bytes

from datetime import*
n=datetime.now();print int(n.strftime('%j'))*86400+n.hour*3600+n.minute*60+n.second

Try it online!

Python 2, 84 bytes

from datetime import*
n=datetime.now();print(n-datetime(n.year,1,1)).total_seconds()

Try it online!

Thanks to @ovs for -21 bytes

\$\endgroup\$
3
  • 1
    \$\begingroup\$ 84 bytes with some datetime arithmetic. \$\endgroup\$
    – ovs
    Mar 5 '21 at 7:01
  • \$\begingroup\$ @ovs thanks a lot \$\endgroup\$
    – wasif
    Mar 5 '21 at 7:02
  • \$\begingroup\$ 81 bytes with another alias \$\endgroup\$
    – movatica
    Mar 8 '21 at 22:04
1
\$\begingroup\$

Bash, 33

dc<<<`date -f- +%s<<<"now
1/1"`-p

Try it online!

Explanation

                     "now\n1/1"     # newline separated now, Jan-1st dates
      date -f- +%s<<<"now\n1/1"     # with -f, date formats multiple lines as multiple seconds-since-1970/01/01
     `date -f- +%s<<<"now\n1/1"`-p  # expands to dc expression to push now-seconds, Jan-1st-seconds, then subtract, then print
dc<<<`date -f- +%s<<<"now\n1/1"`-p  # evaluate the dc expression
\$\endgroup\$
3
  • \$\begingroup\$ Why hasn't this got more upvotes? Is it wrong? \$\endgroup\$
    – user7467
    May 8 '21 at 10:27
  • \$\begingroup\$ The use of -f is tricky enough for an upvote, but 2 separate dates are shorter: Try it online! And without here-string even shorter: Try it online!. \$\endgroup\$
    – manatwork
    May 26 '21 at 8:18
  • \$\begingroup\$ Shorter with a bit more shell power: Try it online! \$\endgroup\$
    – manatwork
    May 26 '21 at 10:21
1
\$\begingroup\$

JavaScript, 83 61 bytes

_=>(new Date()-new Date(new Date().getFullYear()+'-1-1'))/1e3

Yes, it was possible in the end. Could probably shave off a few more bytes. This code outputs the number of seconds since January 1 of the current year, 2021 at the time of writing. Returns a floating point number.

This code does not explicitly output, but running something like

console.log(f())

where f is the function I posted, will output the result

\$\endgroup\$
1
+100
\$\begingroup\$

Vyxal, 26 bytes

kτ‹86400*kḢ3600*+kṀ60*+kṠ+

Try it Online!

For some unknown reason, s flag dosen't work

\$\endgroup\$
1
  • \$\begingroup\$ The s flag sums the top of the stack, so you would have to wrap the stack into a list with the W command. Or, you can use the flag plus some other stuff to get 22 bytes. \$\endgroup\$ May 10 '21 at 16:00
1
\$\begingroup\$

Julia 1.0, 54 bytes

using Dates
f(n=now())=(n-DateTime(year(n))).value/1e3

Try it online!

\$\endgroup\$
1
\$\begingroup\$

R, 60 31 bytes

-difftime(paste0(substr(t<-Sys.time(),1,4),"-01-01"),t,,'s')

using difftime with @Dominic van Essen's new years day replacement method

answer is in the following format:

Time difference of 11203844 secs

TIO_link

rdrr.io link

a much shorter version:

as.double(Sys.time())%%31536000

Try it online!

\$\endgroup\$
3
  • 1
    \$\begingroup\$ difftime is a good golf - well done - but the code here doesn't work as-is: you need to change = to <- inside the call to substr so that t isn't interpreted as a named function agument. \$\endgroup\$ May 10 '21 at 21:58
  • 1
    \$\begingroup\$ (I suggest including a link to 'try it online' like this or to 'rdrr.io' like this so you & others can check the code...) \$\endgroup\$ May 10 '21 at 22:00
  • \$\begingroup\$ Ahhh. you are correct of course. I've tried changing the assignment to '=' and did not copy the correct one. thanks. the byte count was correct though (+1 for <- over = ) \$\endgroup\$
    – Zahiro Mor
    May 11 '21 at 7:28
0
\$\begingroup\$

IBM/Lotus Notes Formula, 33 bytes

@Now-@Date(@Year(@Now);1;1;0;0;0)

Date comparisons return seconds by default. Unfortunately @Date requires the seconds otherwise it constructs a date with the current time.

No TIO for formula so here are a couple of screenshots:

enter image description here

enter image description here

\$\endgroup\$
0
\$\begingroup\$

Wolfram Language (Mathematica), 36 bytes

DateDifference[{2021},Now,"Second"] 

Try it online!

\$\endgroup\$
0
\$\begingroup\$

APL (Dyalog Unicode) 18.0, 16 bytes (SBCS)

Full program

-/20⎕DT↑∘⎕TS¨6 1

Try APL online!

6 1 a 2-element list [6,1]

↑∘⎕TS¨ for each number, take that many elements from the current YMDhmsf list

20⎕DT convert the two dates (the 1-element date is padded with the lowest valid values, i.e. [1,1,0,0,0,0] for the beginning of the 1st of January) to UNIX time (seconds since the beginning of 1970)

-/ difference between them

\$\endgroup\$
0
\$\begingroup\$

05AB1E, 37 bytes

•ΘÏF•ºS₂+žf<£že<ªOŽª+·*žaŽEU*žb60*žcO

Try it online.

Explanation:

•ΘÏF•                   # Push compressed integer 5254545
     º                  # Mirror it to 52545455454525
      S                 # Convert it to a list of digits: [5,2,5,4,5,4,5,5,4,5,4,5,2,5]
       ₂+               # Add 26 to each: [31,28,31,30,31,30,31,31,30,31,30,31,28,31]
         žf             # Push the current month
           <            # Decrease it by 1
            £           # Leave that many leading integers from the list
             že         # Push the current day of the month
               <        # Decrease it by 1 as well
                ª       # Append it to the list
                 O      # Sum it together (total amount of days thus far)
                  Žª+   # Push compressed integer 43200
                     ·  # Double it to 86400
                      * # And multiply it to the amount of days
ža                      # Push the current hours
  ŽEU*                  # Multiply it by compressed 3600
žb                      # Push the current minutes
  60*                   # Multiply it by 60
žc                      # Push the current seconds
O                       # Sum all values on the stack together
                        # (after which the result is output implicitly)

See this 05AB1E tip of mine (section How to compress large integers?) to understand why •ΘÏF• is 5254545; Žª+ is 43200; and ŽEU is 3600.

\$\endgroup\$
0
\$\begingroup\$

Factor, 38 bytes

now now start-of-year time- second>> .

TIO is too old to have start-of-year, so have a screenshot of running the code in the listener. Link to online documentation for the word: https://docs.factorcode.org/content/word-start-of-year,calendar.html

enter image description here

How it works:

Generate two timestamps: one now, and the other at the beginning of the year. Subtract them and then extract the result

\$\endgroup\$
0
\$\begingroup\$

Javascript 25 bytes

Reach 38 with the console.log().

console.log(Date.now()/1e3-1609459200)

\$\endgroup\$
0
\$\begingroup\$

Nim, 59 bytes

import times
echo inSeconds now()-($now().year).parse"YYYY"

Try it on the Nim playground! (For some reason, it doesn't work correctly on TIO.)

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy