0

I tried the following code:

>> import dateutil.parser
>>> date=dateutil.parser.parse("2018-11-23T19:0:09Z")
>>> date.strftime("%s")
'1542996009'

However the returned value 1542996009 correspond to 11/23/2018 @ 6:00pm (UTC) according to https://www.unixtimestamp.com/index.php and it should be 7:00pm

What would be the correct way to get unix timestamp from iso-8601 formatted date string?

Note: Unix timestamp is the number of seconds that have elapsed since 00:00:00 Coordinated Universal Time (UTC), Thursday, 1 January 1970, so I think this is a timezone problem, that is to say the value I got isn't in UTC.

NeDark
  • 1,212
  • 7
  • 23
  • 36
  • NeDark, please [Useful DOC](https://simson.net/page/ISO_8601), i have posted the answer though if helps you can marm kit accepted. – Karn Kumar Nov 12 '18 at 08:24
  • @tripleee The parsing part works, the problem is converting to unix timestamp afterwards.. – NeDark Nov 12 '18 at 08:26
  • I suspected the typo in the minutes field but it seems not to make any difference. – tripleee Nov 12 '18 at 08:31
  • 1
    I *think* the answer lies in the direction of [imperfect time zone semantics](https://stackoverflow.com/a/46053159/874188) but I can't find a proper duplicate right now. – tripleee Nov 12 '18 at 08:37
  • @tripleee, your statement is correct. – Karn Kumar Nov 12 '18 at 08:40
  • Here's a better duplicate: https://stackoverflow.com/questions/11743019/convert-python-datetime-to-epoch-with-strftime – tripleee Nov 12 '18 at 11:07

1 Answers1

1

If you want to get the seconds since epoch, you can use python-dateutil to convert it to a datetime object and then convert it so seconds using the strftime method.

>>> import dateutil.parser as dp
>>> tm = '2018-11-23T19:0:09Z'
>>> tm1 = parsed_t = dp.parse(tm)
>>> tmseconds = parsed_t.strftime('%s')
>>> tmseconds
'1542979809'

Conversion:

>>> datetime.utcfromtimestamp(1542979809).isoformat()
'2018-11-23T13:30:09

'


Karn Kumar
  • 8,518
  • 3
  • 27
  • 53
  • The value you got 1542979809 is 11/23/2018 @ 1:30pm (UTC) according to https://www.unixtimestamp.com/index.php The convertion is bad – NeDark Nov 12 '18 at 08:25
  • I answered, I can add that the code in your answer is the same than the code in question which wasn't working... – NeDark Nov 12 '18 at 08:32
  • I'm thinking any insight provided here should instead be posted as an answer to the proposed duplicate, and the duplicate nomination accepted by the OP. – tripleee Nov 12 '18 at 10:58
  • @tripleee, i posted the answer before it was marked duplicated tough that was not really taken from there otherwise i should not posted it, i took it from my code which i used to in my work. – Karn Kumar Nov 12 '18 at 11:08