EDIT: Basically, I’m looking to do this, in UTC-time, ideally via ISO-8601:
- Python: datetime.datetime —> ISO-8601 string
- Python: ISO-8601 string —> datetime.datetime
- Obj-C: NSDate —> ISO-8601 NSString
- Obj-C: ISO-8601 NSString —> NSDate
This seems like it should be really simple, but I can’t seem to figure it out.
Python code, converting to a string:
>>> import datetime
>>> datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S %z")
'2012-03-08 00:07:31 '
Note that the time-zone info %z is printed as an empty string, since utcnow() returns a naive datetime object. How do I turn it into an aware one and get it to print like the following?
'2012-03-08 00:07:31 +0000'
On the Obj-C side of things:
// This fails and prints (null) since the timezone is missing.
NSString *pythonDate1 = @"2012-03-07 23:51:58 ";
NSDate *objCDate1 = [NSDate dateWithString:pythonDate1];
NSLog(@"%@", objCDate1);
// This works, manually adding in the "+0000".
NSString *pythonDate2 = @"2012-03-07 23:51:58 +0000";
NSDate *objCDate2 = [NSDate dateWithString:pythonDate2];
NSLog(@"%@", objCDate2);
Printout:
2012-03-07 19:14:47.848 Untitled 3[3912:707] (null)
2012-03-07 19:14:47.849 Untitled 3[3912:707] 2012-03-07 23:51:58 +0000
I’m not quite sure how to go back from an NSDate to a datetime.datetime object either. Any help is greatly appreciated! 🙂
if you don’t want to deal with timezone objects, and your time is in UTC, why not just append the “Z” defining Zulu/Zero to the end as defined in ISO-8601
Unless of course Obj-C doesn’t support ISO-8601 formatting…
Or, if your still only going to use utcnow(), you can cheat and just add +00:00: