Time zones and Working with Dates

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

Timezone for a server

Always keep your server's time in UTC. No matter in which time zone your server is in, always configure it to UTC. Because every software, program, programming language, logging systems etc like MySQL, MongoDB, Java, node(JavaScript) will return your server's time when you ask for datetime or timestamp. If you are having all your servers in a single time zone, then it doesn't matter because you can infer about the default time zone based on your server's region. But distributed servers across different regions will produce a lot of problems like out of order logs and data due to timestamps from different time zones and daylight savings.

today() vs now() vs utcnow()

today - return the current local datetime with a timezone of None. now - it gives the option to pass the timezone. utcnow - current utc time, but tzinfo is None. If the host machine is in the UTC timezone then there will be no difference between datetime.datetime.now() and datetime.datetime.utcnow()

Wall clock time

Люди привыкли общаться в терминах «четыре утра» или «семь тридцать вечера». Это называется Wall clock time, то есть время, которое будут показывать часы на стене в данном месте в этот конкретный момент времени.

Что такое неопределенное время?

Скажем, если часы перевели с 2 ночи на 3 ночи, ни в какой момент времени они не покажут 2:30. То есть перевести 2:30 в Unix timestamp не получится — в этом нет смысла. Хуже того, если часы переводят назад (с 3 часов на 2), то 2:30 возникнет на них дважды в день, то есть из 2:30 можно получить аж два разных (с интервалом в 3600000 мс) Unix timestamp-а — преобразование неоднозначно.

How to know what the day would be 5 days from now?

1. Get today's date -> datetime.date.now() 2. Create timedelta -> datetime.timedelta(days=5) return today + delta

Wall time vs Timestamp

- Use Wall Time when it matters the clock on the wall says: meetings, television shows. - Timestamps are specific moments in time: use this when it matters what order things happened in or the duration between two events: logs.

Cколько часов в сутках?

24, правильно? Кроме дней перевода часов, тогда там будет или 23, или 25, потому что для человека сутки — это интервал между 9 утра на часах сегодня и 9 утра на часах завтра, а сколько на самом деле времени прошло — не так уж важно. Важно, во сколько вставать на работу.

Timezone

A time zone is a geographical region where almost everyone observes the same standard time. Have you ever phoned someone in a different country? - If so, they might have been several hours ahead or behind the time it was where you were calling from.

What's a Date in a Calendar?

Basically, calendar represents a series of dates starting from day 0.

Why Are Time Zones Used?

Before the late nineteenth century, most towns and cities across the world used to set their local times based on the observance of stars and the Sun. This was not an issue in and of itself at this time because, for the most part, the differences in time between long distances were barely noticeable due to the very long travel times taken to traverse these distances. However, the latter part of the nineteenth century is well known for the explosion of global trading, and the expansion of communication and transport that inevitably came with this. The Industrial Revolution was in full swing, and the world was changing almost beyond recognition. Because of this, the need eventually arose for a better method of timekeeping. This gave birth to time zones, with the Greenwich Meridian becoming the first, or 'Prime', time zone in 1884.

Issues with Unsync Time

Before we had universally synchronized times and timezones, local time was synchronized to movements of the Sun. Noon was when the Sun was at it's highest point and midnight 12 hours later. Each settlement had their own local times, which could differ by just minutes. This worked fine until trains were invented. Because local times were unsynchronized, trains collided often and schedules confused the passengers. Eventually Railway time was established in England to solve these problems. It was based on local time in London, which you probably know as Greenwich Mean Time or GMT.

Categorization of datetime objects

Date and time objects may be categorized as "aware" or "naive" depending on whether or not they include timezone information.

How does Daylight saving affect UTC?

Daylight saving does not affect UTC. It's just a polity deciding to change its timezone (offset from UTC).

Time delta

Difference between 2 dates or times.

Daylight Savings Time

Do you experience days that get dark earlier during some months of the year, and longer days with more daylight during other months? Some countries adjust their time by one hour twice a year to make better use of the sun during the day. This is called daylight savings time (DST).

Should we always store dt objects in UTC?

Events that have happened in the recent past can safely be saved as UTC. Examples are timestamps for when an email has been sent or a database record has been saved. Your system knows the time in UTC and can save it in UTC. And later you can always convert it to any other time zone. But in the case of future datetimes such as meetings: converting to UTC and saving UTC + timezone name is not resistant to changes in time zone rules. And remember, time zone rules change all the time. UTC is not necessarily the best way to store all date and time values. It works particularly well for past events, or for future absolute events, but it doesn't work so great for future local events - especially future recurring events.

UT1

Это время, основанное на вращении Земли, в предположении, что каждый новый год наступает ровно в 00:00:00 по UT1. Но! Штука в том, что вращение Земли, во-первых, замедляется, а во-вторых неравномерно и непредсказуемо и в итоге каждый год (по астрономическим наблюдениям вращения Земли) имеет слегка разную продолжительность в секундах.

How to Store Dates & Datetimes for Future Events?

For future events, you expect to schedule a meeting / appointment at [Local Time] on [Date] at [Location]. If a time change happens between now and the future event (e.g. daylight savings time), it doesn't matter from the perspective of the meeting because you have a fixed time.

Do timezones follow the line of longitude?

For historical and political reasons, time zone lines are rarely straight. Often, areas that are separated by large distances find themselves in the same time zone, and adjacent areas are in different time zones.

Alarm Clock Problem

If you set your alarm clock by UTC, you'll be waking up an hour early or late on the day of the DST transitions. This is why most folks set their alarm clocks by local time.

Why we should avoid using naive datetimes?

If you think of datetime as a specific point in time, then you should you tz aware datetime, because it's exactly what you want. Using naive datetimes represents any time, basically ambiguous time. UTC-12 to UTC+14 Different times on different systems, local time might differ from server's

Who invented time zones?

In 1876, Canadian engineer Sandford Fleming missed a train in Ireland due to a bad schedule. I guess he was pretty pissed off, since a couple years later he publicly proposed the concept of timezones. He proposed that humans adopt a single universal time, with local time zones being on an offset from it. His idea caught on quick, and 50 years later most countries were using timezones.

Duration

if 2 periods has the same duration, they're equal. If P1 == 1 Day, and P2 == 1 Day, they're equal, but if P1 == 1 Year, and P2 == 1 Year, it doesn't mean those are equal. It's useful to think about duration in terms of minutes, hours, days, but not months or years.

Get current date

There's no such thing as a current date, current date only exists in a timezone. So we need to take a current time of a timezone and get a date from it.

Imagine that it's January 2015 and you're making an appointment in a calendar application for a meeting that will take place in Santiago, Chile on the April 30th at 10:00 in the morning. Your calendar software saves the appointment and you can see that it's there with the description that you made. 2015-04-30 10:00 in Chile. April comes around and you are in Santiago and ready for the meeting you made. You forgot the exact time of the meeting so you check your trusty calendar software on your phone. "Ah yes, it's at 11:00, exactly the time I saved." But when you show up for your meeting you are surprised that actually the meeting was at 10:00 and you are an hour late! How did that happen? Solution

Instead of saving the time in UTC along with the time zone, developers can save what the user expects us to save: the wall time. Ie. what the clock on the wall will say. In the example that would be 10:00. And we also save the timezone (Santiago/Chile). This way we can convert back to UTC or any other timezone.

TAI

International Atomic Time Using atomic clocks in multiple laboratories across the earth, we get the most accurate and constant measure of the second, which allows us to compute time intervals with the highest accuracy.

IANA

Maintains a database of all of the values of time zone offsets. IANA also releases regular updates that include any changes in time zone offsets.

How Time Should Be Stored in Your Program?

Most developers who have worked with time have heard the advice to convert local time to UTC and store that value for later reference. In many cases, especially when you're storing dates from the past, this is enough information to do any necessary arithmetic.

How Computers Count Time?

Nearly all computers count time from an instant called the Unix epoch. This occurred on January 1, 1970, at 00:00:00 UTC.

Unix Time

Number of seconds since 00:00:00 UTC 1 January 1970, excluding leap seconds. Unix time is a means of representing a specific date and time, used by Linux, macOS, and many other interoperable systems.

Best practice for storing time & dates

The best practice is to convert all user input to UTC when received. Don't tell people to "always use UTC everywhere". This widespread advice is shortsighted of several valid scenarios that are described earlier in this document. Instead, use the appropriate time reference for the data you are working with. Timestamping can use UTC, but future time scheduling and date-only values should not.

IANA Database

The database contains a copy of all the designated time zones and how many hours and minutes they're offset from UTC. So, during the winter, when daylight saving time is not in effect, the US Eastern time zone has an offset of -05:00, or negative five hours from UTC. Other regions have different offsets, which may not be integer hours. The UTC offset for Nepal, for example, is +05:45, or positive five hours and forty-five minutes from UTC.

Imagine that it's January 2015 and you're making an appointment in a calendar application for a meeting that will take place in Santiago, Chile on the April 30th at 10:00 in the morning. Your calendar software saves the appointment and you can see that it's there with the description that you made. 2015-04-30 10:00 in Chile. April comes around and you are in Santiago and ready for the meeting you made. You forgot the exact time of the meeting so you check your trusty calendar software on your phone. "Ah yes, it's at 11:00, exactly the time I saved." But when you show up for your meeting you are surprised that actually the meeting was at 10:00 and you are an hour late! How did that happen?

The software did not actually save the time 10:00. Instead it converted the time to UTC (14:00) and saved that along with the timezone of Santiago/Chile. But the software is smart and can convert it back from UTC right? Well that just so happens to be a falsehood. In most cases, yes, you can convert back from UTC to the original timezone. But when timezone rules change, converting back to the original timezone can mean that you get a different result. And that is just what happens in this case. Because Chile has decided to stop using Daylight Saving Time. So what happened was that your software got the newest timezone update. And then when converting back from UTC it used the new rules, while the saved UTC time (14:00) were based on the old rules. With the old rules you would have to subtract 4 hours, but with the new rules only 3. And subtracting 3 hours from 14:00 you get 11:00 instead of 10:00.

In San Francisco on 2:00 AM, March 8th 2015, the time was moved forward 1 hour to transition from Pacific Standard Time (PST) to Pacific Daylight Saving Time (PDT). One second after 1:59:59 AM, the local time was 3:00:00 AM. What's the issue with that?

The times between 2:00:00 AM to 2:59:59 AM did not occur.

How to deal with date representations? - Unix time is how computers count time, but it would be incredibly inefficient for humans to determine the time by calculating the number of seconds from an arbitrary date. - For instance, in the United States, dates are usually written starting with the month, then the day, then the year. This means that January 31, 2020, is written as 01-31-2020. - However, most of Europe and many other areas write the date starting with the day, then the month, then the year. This means that January 31, 2020, is written as 31-01-2020.

To help avoid communication mistakes, the International Organization for Standardization (ISO) developed ISO 8601. This standard specifies that all dates should be written in order of most-to-least-significant data. This means the format is year, month, day, hour, minute, and second: YYYY-MM-DD HH:MM:SS

Leap seconds

To prevent the atomic clocks running away with themselves as Earth slows down, the IERS tries to keep Coordinated Universal Time and Universal Time to within 0.9 seconds of each other. This involves making regular adjustments called 'leap seconds'. A leap second is a one-second adjustment that is occasionally applied to Coordinated Universal Time (UTC), to accommodate the difference between precise time (International Atomic Time (TAI), as measured by atomic clocks) and imprecise observed solar time (UT1).

UTC

UTC stands for Coordinated Universal Time and refers to the time at a longitude of 0°. UTC is often also called Greenwich Mean Time, or GMT. UTC is a standard used to set all time zones around the world. So, for instance, New York City is in the time zone UTC minus five, meaning that it is 5 hours earlier in NYC than the reading on a UTC clock (except during U.S. daylight savings, when it is 4 hours earlier). UTC is not adjusted for daylight saving time, so it consistently keeps twenty-four hours every day. UTC is like a wall time clock in London.

GMT vs UTC

UTC used to be called Greenwich Mean Time (GMT) because the Prime Meridian was (arbitrarily) chosen to pass through the Royal Observatory in Greenwich. Basically, there's no difference between them.

UTC vs TAI vs UT1

UTC это компромисс для удобства обычных людей: это тот же TAI (т.е. атомные стабильные секунды), к которому иногда добавляют или отнимают по одной секунде в год, чтобы Новый год наступал как можно ближе к 00:00:00 по UT1 (астономическому).

What Is the Purpose of Unix Time?

Unix time is a count of total seconds since a fixed time and date. It's a date/time (or timestamp) format that looks different from the human-readable dates and times we're used to. This is purely for efficiency reasons. It takes a lot less space to store a single number representing seconds than it does to store separate values for the year, month, hour, etc.

How to store future events?

When scheduling future events, usually local time is preferred instead of UTC, as it is common for the offset to change.

How to store a timestamp?

When storing a timestamp, store Unix time. It's a single number.

When converting from Local Time to Instant, is it possible to get 0 or more than 1 result?

Yes, it's possible due to DST.

Interval

a period of time between two events, with a specific time associated or anchored.


Set pelajaran terkait

ch 12 ( nursing care of patients having surgery)

View Set

A&P Chapter 7 Skeletal System: Bone Structure and Function

View Set

Grey's Anatomy - Practice Questions

View Set