Computers have a "real-time clock" -- a special hardware device (e.g., containing a quartz crystal) on the motherboard that maintains the time. It is always powered, even when you shut your computer off. Also, the motherboard has a small battery that is used to power the clock device even when you disconnect your computer from power. The battery doesn't last forever, but it will last at least a few weeks. This helps the computer keep track of the time even when your computer is shut off. The real-time clock doesn't need much power, so it's not wasting energy. If you take out the clock battery in addition to removing the main battery and disconnecting the power cable then the computer will lose track of time and will ask you to enter the time and date when you restart the computer.
To learn more, see Real-time clock and CMOS battery and Why does my motherboard have a battery.
Also, on many computers, when you connect your computer to an Internet connection, the OS will go find a time server on the network and query the time server for the current time. The OS can use this to very accurately set your computer's local clock. This uses the Network Time Protocol, also called NTP.