Current date and time in time zone timestamp format

Asked

Viewed 4,376 times

4

How can I print this date in timestamp format with time zone (timestampz)?

from datetime import datetime, timedelta

current_time = (datetime.now())

Upshot:

2019-03-28 15:14:19.108116

I would like you to return in this format:

2019-03-28T15:14:19.000Z

  • 2

    To avoid long discussions in the comments; your conversation was moved to the chat - to proceed just click on the link

3 answers

6


This format you are wanting (2019-03-28T15:14:19.000Z) is defined by the standard ISO 8601.

Either way, this one Z at the end is an important information because indicates that the date/time is in UTC. And as you want the current date and time in UTC, you can’t just use datetime.now() and think you’ll be right.

This is because datetime.now() (when so called, no parameters) will use the system time zone to get the values of the current date and time. My machine, for example, is set to Brasilia Time, which means that today is March 28, 2019, and now it is 5pm. But if the time zone is changed to that of Germany, the time returned will be 9:00, and if you move to Japan, the result will be 29 from March to 5 morning. Already in UTC, the current date and time is 28 March 2019 at 20h.

To get the current date and time values in UTC, use datetime.utcnow(), because this method returns the date and time values in UTC, regardless of the time zone configured in the system.


To format the date using ISO 8601 format, use the method isoformat(). The detail is that in this case will print only the date and time, but not the Z. But if you want, you can add it manually:

from datetime import datetime
print(datetime.utcnow().isoformat() + 'Z')

In that case I add the Z manually, but just because I know utcnow() returns the current date and time in UTC.

If you use now() instead of utcnow() and put the Z at the front, you may be setting a wrong date and time. For example, in my system Timezone is the Brasilia Time and now it is 17h, so the result of datetime.now().isoformat() would be 2019-03-28T17:00:00.000000. If I put the Z in the front stands 2019-03-28T17:00:00.000000Z: 5pm in UTC, which corresponds to 14h in the Time of Brasilia, and this is not the current date/time (but an instant occurred 3 hours before the current date/time). What difference does a "little letter" make, no?

Add the Z manually only "makes sense" using utcnow(), then the result will be in UTC. Use now() will only work in cases of "coincidence" if your system’s Timezone happens to be UTC, or some other one that also uses UTC (such as Timezone London when it’s not in daylight time, for example - yes, when it’s daylight saving, London is an hour ahead of UTC, so even the English should use utcnow()).

If looking at the correct values of date and time is important, even more so if you use values in UTC (actually in any Timezone), because changing the values of the date and time you will end up with completely different instants. The problem will much and only "put a Z at the end of the string".


The code with isoformat() above does not put the Z because a datetime can be naive ("naive") or Aware ("conscious"), and by default utcnow() and now() create an object naive.

Basically, when the datetime is naive, he has no information about the Timezone (time zone), already a Aware has such information. Hence the method isoformat() only returned the date and time. The Z was not printed because the datetime has no information about Timezone, he does not know that his date and time values came from the "current date/time in UTC" returned by utcnow().

But it is possible to create an object Aware passing the timezone.utc for the method now():

from datetime import datetime, timezone

print(datetime.now(timezone.utc).isoformat())

The result is:

2019-03-28T20:00:00.736820+00:00

The problem is that now instead of Z, he prints +00:00, which is a offset: the difference with respect to UTC. In this case, it is zero hours and zero minutes, then +00:00 is the same as UTC, which is the same as Z. So if you want, you can just make a replace:

print(datetime.now(timezone.utc).isoformat().replace('+00:00', 'Z'))

That one replace is correct because now(timezone.utc) returns the current date and time in UTC (independent of the Timezone that is configured in the system), and therefore the offset generated by isoformat() will always be +00:00, which is the same as Z (both mean "UTC"). But if used now() no parameters happen the problems already mentioned above.

0

A possible solution to your problem is to use the method strftime() library datetime. The method formats date objects via input strings. There is a table with the specific formats to mount the string as you wish.

In your case we set up the format the way it is needed, getting:

'%Y-%m-%dT%H:%M:%S.%fZ'

The code of the transformation would be:

from datetime import datetime, timedelta

current_time = datetime.now()    
f_data = current_time.strftime("%Y-%m-%dT%H:%M:%S.%fZ")

print("formated date: "+str(f_data))

Test running

  • 1

    Did what was requested, the downvote should explain why

  • @Sidon My answer explains why, I did not comment before I was writing it: https://answall.com/a/371959/112052

0

Convert to Timezone, replace Timezone (:-)) with Z, add T.

from datetime import datetime, timedelta
current_time = (datetime.now())
print(print(str(current_time)[0:19].replace(' ','T')))

Saida (when I executed)

2019-03-28T16:54:3600Z
  • Could you explain the reason for the downvote? the question asks the exit in a certain format, the two answers you gave negative, does not exactly that? I honestly can’t understand Stopt’s judgment.

  • My answer explains the reason for the downvote, I did not comment before I was writing it: https://answall.com/a/371959/112052

  • Sorry, your answer does not justify the reason for the downvote, I would like to know what is the criterion of a downvote here in English, see in this example what the guy asks: "Specific format in a print", 2 answers are given presenting exactly this and the 2 are negative, and it turns out that although I edited the answer, in the end you make a repàace of the same kind of my first version. :-)

  • Timezone.utc makes all the difference in my replace

  • 1

    Perfectly justified. Only adding Z at the end changes the value - this misrepresents a formatting. The question clearly asked that I wished to have the same date/time in the specific format. And I Gero the date/time in a Timezone other than UTC and just enter the Z at the end I will also be changing the value of the date/time. The date/time 2019-03-28 17:30:17.836555 formatted in the specific pattern is 2019-03-28T20:30:17.836591Z. Notice the difference of 3h between the two formats due to the fact that I am in Timezone -3. Only concatenating the Z your date/time would be for 3h wrong.

  • Okay, @Andersoncarloswoss, I’m aware of that, but look at the context of the question, even after he edited it still remains the same (eqto write this comment), he says: the result: 2019-03-28 15:14:19.108116, i would like: 2019-03-28T15:14:19.000Z (only one replace at the end), see that although he suppressed in the issue, he asked for the difference only in the result of the print(), that is to the print() no matter where the final str comes from. But ok, let’s go ahead.

  • @Sidon Maybe AP did it because they didn’t know the implications of adding Z at the end. Anyway, since it is to answer, we will teach right, it is not even? :)

  • Yes, @hkotsubo, I agree, but it is not because a person has not had the same "insight" as you that he is "teaching wrong" or has bad intentions and deserves to be punished with downvote, Isn’t it? I see similar arguments in Stoen and I find it interesting that it seems to be almost unanimous the opinion of punishing oneself with dv only attempts at cheating, poor quality for sloppiness or carelessness, that is, who, in the end, does not have the genuine intention to help. But I respect your opinion.

  • 1

    @Sidon As far as I know, wrong answers (that do not give the correct result or that explain concepts in a wrong way) deserve negative yes, regardless of intention. But if you edit the answer in a way that gives the correct result or at least puts a warning explaining the limitations of the solution, I will be happy to withdraw the vote :)

  • The @hkotsubo problem is that I don’t consider the result to be incorrect, because for the original question the result was just the presentation @sant0will had the same understanding as me, I didn’t even think it needed anything other than the presentation of a string through the print(), that was the original context, but all right, as I said in another comment, I respect your opinion.

Show 5 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.