Convert timestamp to date / time

I am querying an API and it returns me the date as follows:

"timestamp":"1444253422.348340958"

How to convert this information to date and time using Python?

Author: hkotsubo, 2018-12-13

3 answers

This date format is called Unix time. It is the number of seconds passed since 01/01/1970 emm UTC / GMT.

Using the library datetime you can do this conversion. You will transform this value into a date object that can be manipulated in various ways using datetime. The date can be converted to BRT using datetime methods, but I advise you to do the conversion yourself. See Note

from datetime import datetime
from datetime import timedelta

objeto_data = datetime.fromtimestamp(1444253422.348340958)
print(objeto_data)
data_br = objeto_data - timedelta(hours=3)   #Cuidado com esta conversão. Leia a observação abaixo.
print(data_br)  #imprimir desse jeito fica horrivel, mas voce pode separar cada informacao e imprimir como quiser
texto = str(data_br.day) + "/" + str(data_br.month) + "/" + str(data_br.year) + "  BRT  " + str(data_br.hour) + ":" + str(data_br.minute)
print(texto)

insert the description of the image here

This is probably not the best way to print the date and time, but the important thing is you convert the value in Unix time to a manipulable Date object. With this you have all the flexibility of the datetime library.

-------------------------------------------------------------------

Note: if you need to use Time Zone, see the answer below regarding the pytz library

 1
Author: Rocchi, 2018-12-13 22:03:37

This number is a timestamp , which represents the amount of time elapsed from the Unix Epoch (1970-01-01T00:00Z - 1 January 1970 at midnight UTC).

You usually use a value in seconds or milliseconds, and in your case, it is in seconds. That is, it is a value that represents 1,444,253,422. 348340958 seconds after Unix Epoch. (if it were in milliseconds, would correspond to a date in 1970, so I think more likely to be in seconds even).

Since you want to turn this into a date and time, there is one detail you should take into account. The timestamp represents a point in the timeline: a single instant that is the same worldwide. Only this same moment corresponds to a different date and time, depending on the timezone (time zone). For example, the timestamp 1444253422.348340958 corresponds to the following days and times:

  • in São Paulo: October 7, 2015, at 18:30:22.348340958
  • in London: October 7, 2015, at 22: 30: 22.348340958
  • in Tokyo: 8 October 2015 at 06: 30: 22.348340958
  • in UTC: October 7, 2015, at 21: 30: 22.348340958

Notice that the time is different in each part of the world, and in Tokyo even the day is different (it is also worth noting that in London it is not the same time as UTC-a common myth - because on this day England was in daylight saving time ).

Therefore, if you want to convert a timestamp to a specific date and time, you need to know which timezone will be used.


Modules datetime and pytz

Using the Module datetime, you can convert the timestamp to a date and time. And to work with timezones, up to Python 3.8, I suggest the module pytz, which has support for the timezones of Iana (soon I explain the solution for Python >= 3.9 and because these are better than using timedelta).

But first you need to turn the string "1444253422.348340958" into a number. Since it is not an integer, we can use float, without forgetting to capture the ValueError if the string is not a number.

Next I use datetime.fromtimestamp, passing two parameters:

  • the value of the timestamp (and luckily this method accepts values "with comma", so we can pass the value of the float directly)
  • the timezone that will be used to convert the timestamp to a specific date and time
from datetime import datetime
from pytz import timezone

try:
    # converter string para número
    timestamp = float("1444253422.348340958")

    # converter o timestamp para uma data e hora em um timezone específico
    dt = datetime.fromtimestamp(timestamp, tz = timezone("Asia/Tokyo"))
    print(dt) # 2015-10-08 06:30:22.348341+09:00
    # se quiser mostrar em outro formato
    print(dt.strftime("%d/%m/%Y %H:%M:%S.%f %z")) # 08/10/2015 06:30:22.348341 +0900

    # converter para outro timezone
    dt = dt.astimezone(timezone("Europe/London"))
    print(dt) # 2015-10-07 22:30:22.348341+01:00
    print(dt.strftime("%d/%m/%Y %H:%M:%S.%f %z")) # 07/10/2015 22:30:22.348341 +0100
except ValueError:
    print("não foi possível converter o valor do timestamp para um número")

In this example I used Asia/Tokyo, which made the date and time "October 8, 2015 at 06: 30.22.348341" (the API has microsecond accuracy, i.e. the last 3 digits of the fraction of seconds are lost). Next I converted to Europe/London, which changed both the day and the time (this is to show that the same timestamp actually matches a different date and time, depending on the timezone used). Also note the values +09:00 and +01:00: these are theoffsets (the difference with respect to UTC), which in the case indicate that these times are respectively 9 hours and 1 hour ahead of UTC.

What if I don't specify the timezone in the fromtimestamp method?

print(datetime.fromtimestamp(timestamp))

On my machine the result was 2015-10-07 18:30:22.348341, but this result may vary according to the timezone default used internally (in my case, by the value returned, it seems to be America/Sao_Paulo - the timezone corresponding to the official time of Brasilia). But running on Ideone.com , for example, the result was 2015-10-07 21:30:22.348341 (since probably there the timezone is set to UTC).

So it is important to pass a specific timezone, as the timestamp corresponds to a different date and time in each place in the world. When using fromtimestamp and without specifying a timezone, you lose control over the date / time return.

The names of timezones, such as America/Sao_Paulo, Europe/London and Asia/Tokyo, follow the pattern of IANA , and you can see the full list using all_timezones:

import pytz

print(pytz.all_timezones)

This prints a list with multiple names (more than 500), and you can choose the most suitable one for your situation. For the official time of Brasilia, you can use America/Sao_Paulo (which also has the rules of daylight saving time), but if you want the Northeast zone (which currently does not use Daylight Saving Time) you can use America/Recife or America/Bahia, for example. IANA makes its files available on GitHub, so you can also consult all the timezones of Brazil (all the lines starting with "BR" in this file) and choose what you need.

pytz itself also has this information. Just access the dictionary country_timezones, passing as a key the country code(two letters, according to the ISO 3166 ). In the case, the code of Brazil is "BR", so to know all the timezones of Brazil, just do:

print(pytz.country_timezones['BR'])

This Returns A list with all the names of timezones from Brazil. In the version I am currently using (pytz 2018.7), the return was:

['America/Noronha', 'America/Belem', 'America/Fortaleza', 'America/Recife', 'America/Araguaina', 'America/Maceio', 'America/Bahia', 'America/Sao_Paulo', 'America/Campo_Grande', 'America/Cuiaba', 'America/Santarem', 'America/Porto_Velho', 'America/Boa_Vista', 'America/Manaus', 'America / Eirunepe','America/Rio_Branco']

Choose the one that best suits what you need. Example:

dt = datetime.fromtimestamp(timestamp, tz = timezone("America/Sao_Paulo"))
print(dt)  # 2015-10-07 18:30:22.348341-03:00
# se quiser mostrar em outro formato
print(dt.strftime("%d/%m/%Y %H:%M:%S.%f %z"))  # 07/10/2015 18:30:22.348341 -0300

In this case, I got the date and time in Brasilia Time (America/Sao_Paulo).


Python > = 3.9

From Python 3.9 you can use the module zoneinfo, which already comes installed natively and has support for Iana timezones. The above code would be practically the same, simply replacing the timezone of the pytz by ZoneInfo:

from datetime import datetime
from zoneinfo import ZoneInfo

try:
    # converter string para número
    timestamp = float("1444253422.348340958")

    # converter o timestamp para uma data e hora em um timezone específico
    dt = datetime.fromtimestamp(timestamp, tz = ZoneInfo("Asia/Tokyo"))
    print(dt) # 2015-10-08 06:30:22.348341+09:00
    # se quiser mostrar em outro formato
    print(dt.strftime("%d/%m/%Y %H:%M:%S.%f %z")) # 08/10/2015 06:30:22.348341 +0900

    # converter para outro timezone
    dt = dt.astimezone(ZoneInfo("Europe/London"))
    print(dt) # 2015-10-07 22:30:22.348341+01:00
    print(dt.strftime("%d/%m/%Y %H:%M:%S.%f %z")) # 07/10/2015 22:30:22.348341 +0100

    # usar o timezone do Horário de Brasília
    dt = datetime.fromtimestamp(timestamp, tz = ZoneInfo("America/Sao_Paulo"))
    print(dt)  # 2015-10-07 18:30:22.348341-03:00
    # se quiser mostrar em outro formato
    print(dt.strftime("%d/%m/%Y %H:%M:%S.%f %z"))  # 07/10/2015 18:30:22.348341 -0300
except ValueError:
    print("não foi possível converter o valor do timestamp para um número")

And to see all available timezones, just use zoneinfo.available_timezones:

from zoneinfo import available_timezones

print(available_timezones())

Do not use timedelta

One of the answers suggests the use of timedelta to subtract 3 hours from the date and with this get the "Brazilian time zone". This only works if fromtimestamp returns the date and time in UTC (which we've already seen is not guaranteed if you don't specify the timezone), and if the timestamp matches a date / time when the Brazil is not in daylight saving time (because during daylight saving time the offset becomes -02:00, so only 2 hours should be subtracted).

The problem is that it is very difficult to determine the exact value to be subtracted from UTC, Since Daylight Saving Time rules change all the time. In Brazil, for example: until 2017, Daylight Saving Time started on the third Sunday of October, but from 2018, started on the first Sunday of November. And it will be so "to always", that is, until it changes again - incidentally, it has already changed, Brazil will not have daylight saving time in 2019 (and it will be so until it changes again).

Also, it is not the whole country that adopted daylight saving time. At the time of writing this answer (December 2018), the Northeast states do not adopt, so they use the offset -03:00 all year round. South / Southeast states use -03:00 during part of the year, and in daylight saving time change to -02:00. And the states of Midwest use -03:00 in daylight saving time and -04:00 in "normal"time. But in the North (Amazonas / Pará / etc), they currently do not adopt Daylight Saving Time and use -04:00 all year round, except for Acre, which uses -05:00 all year round (but has already changed these rules several times). And don't forget Fernando de Noronha, who uses the offset -02:00 all year round.

Anyway, using fixed values of timedelta (like -3, or any other value) is inaccurate because you need to know about all of these rules (if a certain region has daylight saving time, when it starts and ends, what offsets are used, etc.), and even "Brazilian time" is something difficult to define, since it depends on which region you are referring to. And that's where Iana comes in: it has a database that already has all this history and you don't have to worry about it. All you need is to know the timezone identifier you want to use (the names America/Sao_Paulo, Europe/London, etc).

Using these identifiers, such as America/Sao_Paulo, it will already know if at the moment that the timestamp represents, that region is or is not in daylight saving time and will use the correct offset (without you having to "guess" and subtract/add arbitrary timedeltas).

This is important because these rules change more than we imagine. Currently America/Recife does not adopt daylight saving time, but in the 80s it adopted. And nothing guarantees that this will not change in the future, since these rules are defined by governments / laws and not always with technical justifications. It is common justifications such as "I want the people to have more hours of sunshine", and even the argument of energy saving and other advantages and disadvantages is debated in various places , and at all times, somewhere in the world, there is someone discussing whether or not to change daylight saving time (that is, the only certainty we have is that these rules change all the time).

Now that Brazil has canceled the schedule in summer, it is tempting to think that we can use a fixed value of timedelta, but nothing guarantees that in the future the government will not adopt it again. Even if it takes time to happen, using a timezone is much more guaranteed, for the reasons already explained above.

So there is a big advantage to using pytz, as it is updated as IANA releases new versions of its bank, and these updates are available on PyPI. Including, they are already aware that Brazil will not have daylight saving time in 2019 and a new version has already been released containing this change.


The use of timedelta is a solution that "seems" right because many do not consider all the rules involving timezones, and think that a fixed offset value is enough.

Except that an offset is not the same as a timezone: the offset is only a fixed numeric value (the difference from UTC, such as +09:00 or -03:00), while a timezone (such as America/Sao_Paulo or Europe/London) has all the history of offsets of a given region (the offset values when it is Daylight Saving Time and when it is not, the exact moments when these changes occur, etc.). For more information, see the "differences between timezone and offset" section in the description of the tag timezone.

 10
Author: hkotsubo, 2020-10-07 11:40:54

Use the datetime module.

Example:

from datetime import datetime
ts = int("1284101485")
print(datetime.utcfromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S'))

Source: SO-Converting unix timestamp string to readable date

 1
Author: LipESprY, 2018-12-13 05:40:28