This repository has been archived by the owner on Jan 13, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 10
/
convert_helper.py
59 lines (51 loc) · 1.64 KB
/
convert_helper.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# -*- coding: utf-8 -*-
"""
@file
@brief Various functions about conversions.
"""
import datetime
def str2datetime(dt, format=None):
"""
convert a string into a datetime object, it can be:
- 2013-05-24 18:49:46
- 2013-05-24 18:49:46.568
@param dt string
@param format format for the conversion, the most complete one is
``%Y-%m-%d %H:%M:%S.%f``
which you get by default
@rtype datetime
@return datetime
"""
if "+" in dt:
dt = dt.split("+")[0].strip()
elif " -" in dt:
dt = dt.split(" -")[0].strip()
if format is None:
if " " in dt:
if "." in dt:
return datetime.datetime.strptime(dt, "%Y-%m-%d %H:%M:%S.%f")
else:
return datetime.datetime.strptime(dt, "%Y-%m-%d %H:%M:%S")
elif "T" in dt:
if "." in dt:
return datetime.datetime.strptime(dt, "%Y-%m-%dT%H:%M:%S.%f")
else:
return datetime.datetime.strptime(dt, "%Y-%m-%dT%H:%M:%S")
else:
return datetime.datetime.strptime(dt, "%Y-%m-%d")
else:
return datetime.datetime.strptime(dt, format)
def datetime2str(dt):
"""
Converts a datetime into a string.
@param dt datetime
@return string
"""
return dt.strftime("%Y-%m-%d %H:%M:%S")
def timestamp_to_datetime(timestamp):
"""
convert a timestamp into a datetime
@param timestamp timestamp
@rtype datetime
"""
return datetime.datetime.utcfromtimestamp(timestamp)